## 5.9. Working with Rational ValuesThe To create a rational number, we use the special method r = Rational(1,2) # 1/2 or 0.5 s = Rational(1,3) # 1/3 or 0.3333... t = Rational(1,7) # 1/7 or 0.14... u = Rational(6,2) # "same as" 3.0 z = Rational(1,0) # error! An operation on two rationals will typically be another rational: r+t # Rational(9, 14) r-t # Rational(5, 14) r*s # Rational(1, 6) r/s # Rational(3, 2) Let's look once again at our floating point inaccuracy example (see section 5.4, "Comparing Floating Point Numbers"). In the following example, we do the same thing with rationals rather than reals, and we get the "mathematically expected" results instead: x = Rational(1000001,1)/Rational(3,1000) y = Rational(3,1000)*x if y == 1000001.0 puts "yes" # Now we get "yes"! else puts "no" end Some operations, of course, don't always give us rationals back. x = Rational(9,16) # Rational(9, 16) Math.sqrt(x) # 0.75 x**0.5 # 0.75 x**Rational(1,2) # 0.75 However, the |

The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)

ISBN: 0672328844

EAN: 2147483647

EAN: 2147483647

Year: 2004

Pages: 269

Pages: 269

Authors: Hal Fulton

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net