5 ms·
Isn't it an expected behaviour (at least for programmers) because of IEEE 754? For example, in Racket this also gives 2.0, but if you are using exact numbers (
by kovrik 10y ago
Isn't it an expected behaviour (at least for programmers) because of IEEE 754?
For example, in Racket this also gives 2.0, but if you are using exact numbers (#e), then it gives exact and correct answer 1.0.
Same for Java (and any other language): if you are using Float/Double numbers, then you are loosing precision. Use BigDecimal (or something similar for other languages) if you want exact calculations.
- kovrik 10y agoUPD: But interesting question though: if language X gives correct answer for that example (without using special classes and functions), does that mean that language X is not following IEEE 754 and does something else under the hood, hence will be much slower? Take, for example, Java: no one is using BigInteger/BigDecimal by default because they are waaay much slower. You can't have precision for free, can you?
- deleted 10y ago[deleted]
- MaulingMonkey 10y agoSome dynamically typed languages use hybrid approaches - e.g. Ruby has Fixnum and Bignum for integers - but you're correct that additional precision isn't free. I don't know how much slower, but in theory such hybrid approaches can allow the common case to be just as fast or fast enough (tm) while still returning the correct results for the uncommon case (depending on how much the runtime or compiler can prove about the range of your numbers to enable the fast path.) EDIT: Poor phrasing...
- Waterluvian 10y agoYeah. And Decimal in Python would return the correct value too.
- PDoyle 10y agoIf there's a problem here, it's that large integers are being treated as floating-point numbers with insufficient precision to represent them properly. With the exception of Perl 6 (?!), programming languages all seem to agree that putting a period in a number gives them a license to return answers that don't agree with normal arithmetic. If you think about it, that's an odd thing to be unanimous about. Also, BigDecimal doesn't give "exact calculations" unless you stick to numbers with finite decimal expansions. BigDecimal can't do 1/3 without rounding.