Hacker News new | comments | show | ask | jobs | submit login

I really like the approach Perl 6 takes with FatRat[1]. You basically have an object which holds a numerator and denominator, so all arithmetic calculations do not loose precision.

[1] https://docs.perl6.org/type/FatRat




Rational numbers don't lose precision, but the compromise is that they can get arbitrarily large after a series of calculations, even if the calculations themselves involve small numbers.

Having access to rational numbers is great and there are times they are incredibly useful, but I don't think it's a good default.


For monetary values, though, the denominators should be the same.

This means that the denominator won't get arbitrarily large.

For serious uses of rationals you need to have control over when the top and bottom are divided by the GCD. For currency you want to keep the denominator at 100. 50/100 wants to remain as that and not get simplified to 1/2.


If you have a constant denominator, you don't need it. It's just a unit.


Ever seen the numeric tower of lisp? https://en.wikipedia.org/wiki/Numerical_tower

The link to the scheme documentation that goes over this is quite good.


That's fantastic! Do you have any more resources on this? I'd like to look at that concept in more depth.


Nothing specific. The scheme manual linked is a good one. As are the docs for Common Lisp. https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node16.html

Honestly, most all older manuals and documents that were not related to systems programming seem to cover numeric programming decently enough. I get the impression that languages used to worry more about that sort of thing, but then the truly heavy lifting of numeric programming moved into the specialized domains of Matlab and friends, and then programmers slowly unlearned most of what was learned regarding numbers.


Clojure does this out of the box: `(/ 1 3)` is 1/3. Removes a lot of annoying floating point errors.


Adding to the languages that do this, Factor does as well. "1 3 /" produces the rational value "1/3". https://docs.factorcode.org/content/article-rationals.html


Floating point arithmetics is not the only problem. See bankers rounding.


Yes, but bankers rounding should be the last step in calculation, not an intermediate.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: