Ruby: converting from float to integer in ruby produces strange results?

Actually, all of this make sense. Because 0.8 cannot be represented exactly by any series of 1 / 2 ** x for various x, it must be represented approximately, and it happens that this is slightly less than 10015.8. So, when you just print it, it is rounded reasonably. When you convert it to an integer without adding 0.5, it truncates .79999999... to .7 When you type in 10001580.0, well, that has an exact representation in all formats, including float and double.

So you don't see the truncation of a value ever so slightly less than the next integral step. Floating point is not inaccurate, it just has limitations on what can be represented. Yes, FP is perfectly accurate but cannot necessarily represent every number we can easily type in using base 10.

(Update/clarification: well, ironically, it can represent exactly every integer, because every integer has a 2 ** x composition, but "every fraction" is another story. Only certain decimal fractions can be exactly composed using a 1/2**x series.) In fact, JavaScript implementations use floating point storage and arithmetic for all numeric values. This is because FP hardware produces exact results for integers, so this got the JS guys 52-bit math using existing hardware on (at the time) almost-entirely 32-bit machines.

Thanks! I never thought I could hit any of the accuracy problems on such a small numbers. – tosu Mar 10 at 5:22 @tosu Nothing to do with small number.It is the way computers deals with floating point numbers.

– Dmytrii Nagirniak Mar 10 at 5:45 1 @tosu: It's not so much an accuracy problem as it is a representation problem. Floats are represented in the source code in decimal but in RAM in binary. This means that numbers which look like they should have a finite representation (i.e.

In your case 4/5) actually have an infinite representation (IOW: no matter how accurate you make your floats, you still would get rounding errors). The problem is that there is a cognitive disconnect between what you see and what you get: you wouldn't be surprised at all that 1/3 has an infinite representation, but for 1/10 it's not obvious. – Jörg W Mittag Mar 10 at 6:37.

Due to truncation error in float calculation, 10015.8*100.0 is actually calculated as 1001579.999999... So if you simply apply to_i, it cuts off the decimal part and returns 1001579.

en.wikipedia.org/wiki/Floating_point#Acc... >> sprintf("%.16f", 10015.8*100.0) => "1001579.9999999999000000" And Float#to_i truncates this to 1001579.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions