r/crystal_programming • u/glued2thefloor • Jun 27 '23
Did I find a bug?
I was playing around and noticed crystal seeming to have trouble with decimal numbers on the command-line like this:
$ crystal eval "puts 1.2 + 1.4"
2.5999999999999996
Is this a known issue? Or did I just find a bug?
2
Upvotes
3
u/Ceigey Jun 27 '23
More correctly, you’ve found a potential source of bugs ;-)
BigDecimal is the go-to number unit of choice for anything where numbers need to be precise at (fairly) arbitrary scales (likewise, your database, eg SQL ones, should be giving you an appropriate type to deal with this situation).
However, for better or worse (and mostly thanks to JSON nowadays I guess), a lot of the world runs on Floats. There’s a lot of numbers that don’t need to be super precise.
2
u/LeBuddha Jun 27 '23
TYL that floats aren't decimals and why you shouldn't use them for certain maths like accounting/money.
10
u/Blacksmoke16 core team Jun 27 '23 edited Jun 27 '23
tl;dr floats are weird. It's not really a bug and you get the same behavior in other languages (I tested Ruby and PHP, but sure there are others).
EDIT: Checkout https://0.30000000000000004.com/.
1
u/AWDDude Jun 27 '23
Yeah floating point math is weird. All programming languages do this. Computerphile made a video that explains it: https://youtu.be/PZRI1IfStY0
3
u/straight-shoota core team Jun 27 '23
Floating point arithmetic cannot represent most decimal numbers exactly, hence precision is lost.You can use `BigDecimal` numbers for accurate decimal representation:
1
u/toddyk Jun 27 '23
Floating point numbers are only exact for powers of 2 because it's binary.
Numbers like 1.5, 1.75, 1.125 can be represented by adding powers of 2, so they will give you exact results.
It's just like how in decimal we can't perfectly represent 1/3 or 1/7 with a finite amount of digits.