From: Todd Benson Date: 2008-09-15T01:08:39+09:00 Subject: Re: how do deal with huge numbers and keep them accurate? On Sun, Sep 14, 2008 at 10:47 AM, Todd Benson wrote: > On Sun, Sep 14, 2008 at 7:18 AM, Tomi Zzzz wrote: >> Hello all, I wrote the following code: >> >> require "bigdecimal" >> require "bigdecimal/math" >> include BigMath >> odd = gets.chomp.to_f >> result = odd/3.0 >> puts result.to_f >> blank = gets.chomp >> >> the code works just fine when the input is upto 15 digits, but >> afterwards the code fails to give the correct output. >> >> a few good examples: >> odd=1231231 >> result=410410.333333333 >> >> odd=123123123123121 (15 digits) >> result=41041041041040.3 >> >> so far so good,now: >> odd=1231231231231231 (16 digits) >> result=4.1041041041041e+014 (given with no remainder) >> [It's a wrong answer! the result should have been --- >> 410410410410410.33333] >> >> What do i need to chance in the code to make it happen? >> in the future i should deal with larger numbers and the accuracy is >> essential. >> >> thanks in advanced, tomi. > > require 'bigdecimal' > require 'bigdecimal/math' > include BigMath > a = BigDecimal('1231231231231231') > b = 3.0 > puts a/b > b = BigDecimal('3') > puts a/b Oops, didn't clarify. What Rick said, but make sure your denominator is also a BigDecimal instance. Least common denominator operation (Float object), I suppose. Todd