File: bfloat16_test.go

package info (click to toggle)
golang-github-d4l3k-go-bfloat16 0.0~git20211005.690c3bd-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 84 kB
  • sloc: makefile: 2
file content (53 lines) | stat: -rw-r--r-- 1,016 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package bfloat16

import (
	"crypto/rand"
	"reflect"
	"testing"
)

func randomBytes(n int) []byte {
	out := make([]byte, n)
	if _, err := rand.Read(out); err != nil {
		panic(err)
	}
	return out
}

func TestEncodeDecode(t *testing.T) {
	b := randomBytes(1024)
	bf16 := Decode(b)
	out := Encode(bf16)
	if !reflect.DeepEqual(b, out) {
		t.Fatalf("%+v != %+v", b, out)
	}
}

func TestEncodeDecodeFloat32(t *testing.T) {
	b := randomBytes(1024)
	bf16 := DecodeFloat32(b)
	out := EncodeFloat32(bf16)
	if !reflect.DeepEqual(b, out) {
		t.Fatalf("%+v != %+v", b, out)
	}
}

func TestBasicFloat32(t *testing.T) {
	var in float32 = 1.0
	out := ToFloat32(FromFloat32(in))
	if !reflect.DeepEqual(in, out) {
		t.Fatalf("%+v != %+v", in, out)
	}
}

func TestComplexFloat32(t *testing.T) {
	var in float32 = 123456789123456789.123456789
	var want float32 = 123286039799267328.0
	out := ToFloat32(FromFloat32(in))
	if in == out {
		t.Fatalf("no loss of precision")
	}
	if out != want {
		t.Fatalf("%.16f != %.16f", want, out)
	}
}