3

Why is 57.5 not same as 57.5? For example:

> b = 57.5
> print (57.5 == b)
true

> c = 0.575 * 100    
> print (c)
57.5

> print (c == b)
false

> print (c, b)
57.5    57.5

So somehow even though both c and b is 57.5, the numbers are not equal

Is there perhaps a rounding issue? but shouldn't the numbers print differently if that's so?

Edit: Excellent, is there a way to print the actual value in LUA? Like if I want it to print 57.4999999999...?

Alex
  • 1,192
  • 14
  • 30

3 Answers3

3

It's the same reason (1/3) * 3 won't give you the same result as 1 in fixed-precision decimal arithmetic. There is no representation that can be multiplied by 3 to give 1 in fixed-precision decimal.

They print the same because the printing code rounds the output. Would you want (1/3) * 3 to print as .999999999999999 or 1?

Try this:

b = 57.5
c = 0.575 * 100
print (string.format("b = %.24f", b))
print (string.format("c = %.24f", c))

Output is:

b = 57.500000000000000000000000
c = 57.499999999999992894572642
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • I'm not sure if I want to print .999... or 1 in general case, but is there a way to print that value as .999...? – Alex Nov 20 '13 at 19:42
3
b=57.499999999999996
c = 0.575 * 100   
print (c==b)

This will return True. Actually, If you enter .575

"%.17f" % 0.575 

it returns 0.57499999999999996.

lennon310
  • 12,503
  • 11
  • 43
  • 61
2

In response to your edited question of how to print the number with greater precision, it's roughly the same as it is in C with printf.

> =string.format('%.17f', 0.1)
0.10000000000000001

Please see this question as well.

As for the issues relating to floating point numbers, they've been covered numerous times in the past in other places. There's an informative link given in the comments that I'll copy here.

Community
  • 1
  • 1
Ryan Stein
  • 7,930
  • 3
  • 24
  • 38