Commit c181d1e7 authored by Ray Chason's avatar Ray Chason

Implement Complex#abs in terms of Math.hypot

Math.hypot avoids premature overflow and underflow
parent 438638b4
...@@ -62,7 +62,7 @@ class Complex < Numeric ...@@ -62,7 +62,7 @@ class Complex < Numeric
end end
def abs def abs
Math.sqrt(abs2) Math.hypot imaginary, real
end end
alias_method :magnitude, :abs alias_method :magnitude, :abs
......
...@@ -70,6 +70,14 @@ end ...@@ -70,6 +70,14 @@ end
assert 'Complex#abs' do assert 'Complex#abs' do
assert_float Complex(-1).abs, 1 assert_float Complex(-1).abs, 1
assert_float Complex(3.0, -4.0).abs, 5.0 assert_float Complex(3.0, -4.0).abs, 5.0
if 1e39.infinite? then
# MRB_USE_FLOAT in effect
exp = 125
else
exp = 1021
end
assert_true Complex(3.0*2**exp, 4.0*2**exp).abs.finite?
assert_float Complex(3.0*2**exp, 4.0*2**exp).abs, 5.0*2**exp
end end
assert 'Complex#abs2' do assert 'Complex#abs2' do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment