bfloat16_test.go 1016 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package bfloat16
  2. import (
  3. "crypto/rand"
  4. "reflect"
  5. "testing"
  6. )
  7. func randomBytes(n int) []byte {
  8. out := make([]byte, n)
  9. if _, err := rand.Read(out); err != nil {
  10. panic(err)
  11. }
  12. return out
  13. }
  14. func TestEncodeDecode(t *testing.T) {
  15. b := randomBytes(1024)
  16. bf16 := Decode(b)
  17. out := Encode(bf16)
  18. if !reflect.DeepEqual(b, out) {
  19. t.Fatalf("%+v != %+v", b, out)
  20. }
  21. }
  22. func TestEncodeDecodeFloat32(t *testing.T) {
  23. b := randomBytes(1024)
  24. bf16 := DecodeFloat32(b)
  25. out := EncodeFloat32(bf16)
  26. if !reflect.DeepEqual(b, out) {
  27. t.Fatalf("%+v != %+v", b, out)
  28. }
  29. }
  30. func TestBasicFloat32(t *testing.T) {
  31. var in float32 = 1.0
  32. out := ToFloat32(FromFloat32(in))
  33. if !reflect.DeepEqual(in, out) {
  34. t.Fatalf("%+v != %+v", in, out)
  35. }
  36. }
  37. func TestComplexFloat32(t *testing.T) {
  38. var in float32 = 123456789123456789.123456789
  39. var want float32 = 123286039799267328.0
  40. out := ToFloat32(FromFloat32(in))
  41. if in == out {
  42. t.Fatalf("no loss of precision")
  43. }
  44. if out != want {
  45. t.Fatalf("%.16f != %.16f", want, out)
  46. }
  47. }