Reputation: 1405
The problem is simple and strange! I wrote a program in Delphi and used roundto function. In one computer 1.5 is rounded to 2 and in another computer it is rounded to 1. How could this happen?
P.S: Code------> Roundto(1.5, 0)
P.S 2: It seems more information is needed so I post more exact detail. I wrote a program. They entered two number: a=7231.76 b=3556.71 Now they can enter a third number c if c >= a - b but the exact formation in my code is
`roundto(c, -1) >= roundto(a, -1) - roundto(b, -1)`
`roundto(a, -1) = 7231.8`
`roundto(b, -1) = 3556.7`
so
`roundto(a, -1) - roundto(b, -1) = 3675.1`
they entered
`c = 3675.05`
I traced the program. In one computer it says round(c, -1) = 3675.1
and in another computer it says round(c, -1) = 3675.0
Upvotes: 3
Views: 3613
Reputation: 111810
I would say you encountered the "banker's rounding" problem, and you posted the wrong data :-) Delphi RoundTo implements the banker's rounding: Odd numbers that end in .5 are rounded upwards, that's the traditional behavior, but... Even numbers that end in .5 are rounded downwards! So 1.5 is rounded to 2.0, but 2.5 is rounded to 2.0 (link to a reference of RoundTo)
Second possibility: http://www.merlyn.demon.co.uk/pas-chop.htm#DRT there is a bug in certain versions of Delphi. Do you have the same version of Delphi in all the machines?
Third possibility: you are speaking of floating points! They aren't exact numbers! Adding and subtracting them creates a microworld of decimals normally invisible 0.1 + 0.2 != 0.3!! Perhaps what you see as .5 isn't exactly .5 but is .49999999 or .500000001. If you want to check it, step into the debugger and check if c = 3675.05
(the logical expression) is true or false, if round(c, -1) = 3675.1
is true or false and so on. If you want to explore the fp world, try this: http://pages.cs.wisc.edu/~rkennedy/exact-float
Fourth possibility: the rounding of 3675.05 changes if you are using Single or Double. With Single it's 3675.1, with Double it's 3675 :-) Ah... the magical world of floats :-)
When you want to make mathematical tricks, please use the Currency type (it is a fixed point number and doesn't have these problems).
There is a last possibility, but it's quite improbable: the Intel CPU stores intermediate results of Double operations as 80 bits fp and then "round" them to 64 bits on output. Some compilers/languages introduce an optional optimization (that is activated on the run of the program if possible) to use the SSE2 opcodes present in some processors instead of the FPU of the processor. The SSE2 operate on 64 bits fp, so no upcasting to 80 bits and downcasting from 80 bits. This could cause what you are seeing. Read here Differences between x87 FPU and SSE2.
Upvotes: 9