From: oinkoink+unet@... (Bret Jolly) Date: 2003-05-04T03:52:09+09:00 Subject: Re: MathN Dave Thomas wrote in message news:<3EA7FF8F.3080500@pragprog.com>... > I'm trying to get to grips with the 'mathn' library. I can see what it > _does_, but I'm trying to see why it does it. Is it emulating a mathn > library in some other language, or is it simply there to make arithmetic > more accurate? Let me try again, since the usenet gremlins seem to have intercepted my earlier post (although Jim Freeze saw it somehow). The easiest way to see the importance of the mathn library is to consider what happens if you try to use Rational, Complex, or Matrix, without requiring mathn. (The mathn library requires rational.rb, complex.rb, and matrix.rb. and then makes them "play nice" with one another.) First look at complex numbers without mathn. irb(main):001:0> require 'complex' true irb(main):002:0> minus_two = Complex(-2, 0) Complex(-2, 0) irb(main):003:0> minus_two < 1 false # fubar! irb(main):004:0> minus_two > 1 true # fubar! irb(main):001:0> require 'mathn' true irb(main):002:0> minus_two = Complex(-2, 0) -2 irb(main):003:0> minus_two < 1 true # correct irb(main):004:0> minus_two > 1 false # correct Now try matrix.rb irb(main):001:0> require 'matrix' true irb(main):002:0> m = Matrix[[2, 7], [3, 4]] Matrix[[2, 7], [3, 4]] irb(main):003:0> m.det -6 # fubar! irb(main):004:0> m.inv Matrix[[-1, 1], [0, -1]] # fubar! irb(main):001:0> require 'mathn' true irb(main):002:0> m = Matrix[[2, 7], [3, 4]] Matrix[[2, 7], [3, 4]] irb(main):003:0> m.det -13 # correct irb(main):004:0> m.inv Matrix[[-4/13, 7/13], [3/13, -2/13]] # correct Now try rational.rb irb(main):001:0> require 'rational' true irb(main):002:0> two = Rational(2, 1) Rational(2, 1) irb(main):003:0> 2 == two true # Gratifying, but... irb(main):004:0> two/3 Rational(2, 3) irb(main):005:0> 2/3 0 # inappropriate when Rational is available. # equal numbers should act equal! irb(main):001:0> require 'mathn' true irb(main):002:0> two = Rational(2, 1) 2 irb(main):003:0> two/3 2/3 irb(main):004:0> 2/3 2/3 # integers and rationals now play nice In conclusion, if you want to use the built-in libraries rational, complex, and matrix, you should require mathn. Regards, Bret