Class: Struct::Float::Test

Inherits:
Test::Unit::TestCase
  • Object
show all
Defined in:
lib/struct_float.rb

Overview

Tests Struct::Float.

Instance Method Summary collapse

Instance Method Details

#assert_consistent(f, s) ⇒ Object



73
74
75
76
77
78
# File 'lib/struct_float.rb', line 73

def assert_consistent(f,s)
  assert_equal(f,s.to_f)
  assert_equal(s,f.to_struct)
  assert_equal(s, eval(s.inspect))
  assert(f.ulp.infinite? || (f/f.ulp).to_i == f/f.ulp, [f,f.ulp].inspect)
end

#assert_nan(s) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
# File 'lib/struct_float.rb', line 80

def assert_nan(s)
  # NaN does not have a unique representation, and therefore
  # it does not make sense to have it as a constant as for
  # Infinity. In particular a NaN has 2047 as biased exponent and
  # non-zero fraction
  assert(2047, s.biased_exp)
  assert(!s.fraction.zero?, s.fraction)
  # You cannot test for NaN with equality. You MUST use nan?
  assert(s.to_f.nan?, s.to_f)
  assert_equal(s, eval(s.inspect))
end

#test_consistencyObject



92
93
94
95
96
97
98
99
100
101
# File 'lib/struct_float.rb', line 92

def test_consistency
  assert_consistent Infinity, Struct::Float[1,2047,0]
  assert_consistent -Infinity, Struct::Float[-1,2047,0]
  assert_consistent 2.0 ** -1074, Struct::Float[1,0,1]
  assert_consistent 0.0, Struct::Float[1,0,0]
  assert_consistent -0.0, Struct::Float[-1,0,0]
  assert_consistent 1.0, Struct::Float[1,1023, 0]
  assert_consistent 1/3.0, Struct::Float[1,1021,0x5555555555555]
  assert_consistent 1/5.0, Struct::Float[1,1020,0x999999999999a]
end

#test_denormalizedObject



109
110
111
# File 'lib/struct_float.rb', line 109

def test_denormalized
  assert_consistent 34 * 2.0 ** -(1023+51), Struct::Float[1,0,34]
end

#test_nanObject



103
104
105
106
107
# File 'lib/struct_float.rb', line 103

def test_nan
  assert_nan( (0.0/0.0).to_struct)
  assert_nan( Struct::Float[-1,2047,34])
  assert_nan( Struct::Float[+1,2047,34])
end

#test_normalizedObject



113
114
115
# File 'lib/struct_float.rb', line 113

def test_normalized
  assert_consistent -(2**52+34) * 2.0**(1043-1023-52), Struct::Float[-1,1043,34]
end

#test_samplesObject



117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/struct_float.rb', line 117

def test_samples
  n = 1000
  srand 12345
  n.times{
    s = Struct::Float[2*rand(2) -1, rand(2048), rand(2**52)]
    f = s.to_f
    if f.nan?
      assert_nan(s)
    else
      assert_consistent(f,s)
    end
  }
end