4 ms·
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
by b2ccb2 8y ago
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 https://docs.perl6.org/type/FatRat
- taeric 8y agoEver seen the numeric tower of lisp? https://en.wikipedia.org/wiki/Numerical_tower https://en.wikipedia.org/wiki/Numerical_tower The link to the scheme documentation that goes over this is quite good.
- b2ccb2 8y agoThat's fantastic! Do you have any more resources on this? I'd like to look at that concept in more depth.
- taeric 8y agoNothing 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 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.
- christophilus 8y agoClojure does this out of the box: `(/ 1 3)` is 1/3. Removes a lot of annoying floating point errors.
- doublec 8y agoAdding 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 https://docs.factorcode.org/content/article-rationals.html
- tikhonj 8y agoRational 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.
- dpwm 8y agoFor 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.
- Retra 8y agoIf you have a constant denominator, you don't need it. It's just a unit.
- ed_balls 8y agoFloating point arithmetics is not the only problem. See bankers rounding.
- b2ccb2 8y agoYes, but bankers rounding should be the last step in calculation, not an intermediate.