rawify / Fraction.js

Fraction is a rational numbers library written in JavaScript
https://raw.org/article/rational-numbers-in-javascript/
MIT License
598 stars 69 forks source link

Not precise enough #12

Closed whitejava closed 5 years ago

whitejava commented 7 years ago

It's not precise enough:

        var a = fraction('1.00001');
        var b = fraction('3.2000000000001');
        var actual = a.add(b); // get 4.200010000000099 but expect 4.2000100000001

I use it for money calculation, so this behaviour is not acceptable.

dekuenstle commented 7 years ago

The fractions are still represented internally with floats for numerator and denominator. Therefore you can run in approximation and representation problems like you usually do with floats (see https://stackoverflow.com/a/2100502). For money, better use something which is based on an (almost infinit) decimal representation with the cost of runtime speed (like decimal.js).

JensGrabner commented 7 years ago

This script works fine: http://czurnieden.github.io/bernoulli.html

infusion commented 7 years ago

Thanks for reporting this issue. We discuss this issue for quite some time now. Fraction.js isn't meant to be an arbitrary precision library (yet). It's a performance tradeoff between having a fast library and a library like decimal.js or the library Jens mentioned, which extends to rational numbers. @josdejong We should definitely think about an arbitrary precision version, for complex.js, fraction.js and quaternion.js. The question is, what is the best way to tackle this issue. Either duplicate the original source file and add an abstract version. Another way would be to create completely new projects (which I don't like, I would keep it in one project where the user can decide). As for math.js, there is already decimal.js embedded. As such the definition of the abstract type would be quite easy (plus including a different source file). What do you think?

infusion commented 6 years ago

@josdejong Have you seen https://developers.google.com/web/updates/2018/05/bigint ? :) This looks pretty promising and I will extend the library as soon as it is in node.js.

josdejong commented 6 years ago

Yes, this is really great!

See also https://github.com/josdejong/mathjs/issues/1096

josdejong commented 6 years ago

It would be nice and powerful if Fraction.js could handle "any" numeric type: number, bigint, BigNumber. We've discussed something like that in the paste in https://github.com/josdejong/mathjs/issues/694

infusion commented 6 years ago

Hmm, for complex.js this might make sense. Fraction.js can handle any input type, but I think internally the new way to go should be BigInt. For the implementation, I will create a simple polyfill for BigInt, which operates on number like before. Maybe I'll add a constant which indicates if full BigInt support is available.

infusion commented 5 years ago

Please see #28