From: serialhex Date: 2011-05-12T22:54:21+09:00 Subject: Re: Math cube root --00151759312aea886c04a3148470 Content-Type: text/plain; charset=ISO-8859-1 On Thu, May 12, 2011 at 8:25 AM, Josef 'Jupp' Schugt wrote: > On Wed, 11 May 2011 21:45:42 +0200, Sergey Avseyev < > sergey.avseyev@gmail.com> wrote: > > How can you explain this: >> >> $ irb >> 1.9.2p180 (main):001:0> 1000 ** (1.0/3) >> 9.999999999999998 >> 1.9.2p180 (main):002:0> Math.sqrt(100) >> 10.0 > > instead of using floats you can try to use rational numbers in ruby: ruby-1.9.2-p180 :001 > require 'mathn' => true ruby-1.9.2-p180 :002 > 1000 ** (1.0/3) => 9.999999999999998 ruby-1.9.2-p180 :003 > 1000 ** (1/3) => 10 ruby-1.9.2-p180 :004 > 1.0/3 => 0.3333333333333333 ruby-1.9.2-p180 :005 > 1/3 => (1/3) you need to require 'mathn' which will change integer division (and make all the numbers play nicely together) but other than that things will work better. the only down side to this whole thing is that rationals are slower than floats (probably significantly so) because it is a pair of integers. and some values when you look at them wont seem to make sense as a rational, like PI: ruby-1.9.2-p180 :011 > Math::PI => 3.141592653589793 ruby-1.9.2-p180 :012 > Math::PI.to_r => (884279719003555/281474976710656) you can always num.to_f back but that also takes time. one last thing: if your inputs are floats i'm not sure there is a nice way to convert them to rationals: ruby-1.9.2-p180 :016 > (1.0/3).to_r => (6004799503160661/18014398509481984) ruby-1.9.2-p180 :017 > 1/3 => (1/3) so this entire e-mail may be moot :P hex --00151759312aea886c04a3148470--