Skip to content

Commit 69fce25

Browse files
Fix float when min and max are too far apart (#225)
Rearrange the arithmetic expression such that intermediate operations are always within the bounds of floating-point numbers that can be represented by the system. - Fixes ArithmeticError exception when max - min >= 1.79e308. - Fixes floats generated outside of [min, max] range when upper/lower limits were lost due to loss of significance.
1 parent 5d45b3a commit 69fce25

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

‎lib/stream_data.ex‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1753,7 +1753,7 @@ defmodule StreamData do
17531753
exponent_data = integer(0..min(size, 1023))
17541754

17551755
bind(exponent_data, fn exponent ->
1756-
map(float_in_0_to_1(exponent), fn float -> float * (max - min) + min end)
1756+
map(float_in_0_to_1(exponent), fn float -> float * max + min * (1.0 - float) end)
17571757
end)
17581758
end)
17591759
end

‎test/stream_data_test.exs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,20 @@ defmodule StreamDataTest do
294294
end
295295

296296
describe "float/1" do
297+
test "generates floats close to system limit" do
298+
[min, max] = [-9.0e307, 9.0e307]
299+
float = float(min: min, max: max) |> Enum.at(0)
300+
assert float >= min and float <= max
301+
end
302+
303+
property "with a large negative :min and :max option" do
304+
# The large negative min might cause loss of significance.
305+
check all float <- float(min: -9.9e25, max: -1) do
306+
assert is_float(float)
307+
assert float <= -1
308+
end
309+
end
310+
297311
property "without bounds" do
298312
check all float <- float() do
299313
assert is_float(float)

0 commit comments

Comments
 (0)