Coder Social home page Coder Social logo

mikemcl / decimal.js Goto Github PK

View Code? Open in Web Editor NEW
6.1K 74.0 478.0 8.54 MB

An arbitrary-precision Decimal type for JavaScript

Home Page: http://mikemcl.github.io/decimal.js

License: MIT License

JavaScript 99.89% HTML 0.11%
javascript bignumber arbitrary-precision significant-digits trigonometric-functions bigdecimal

decimal.js's People

Contributors

2color avatar adrianhara avatar chrisguttandin avatar dmarkow avatar harrysarson avatar hypercubed avatar jon-ressio avatar jonahbron avatar luciavelasco avatar lukaskollmer avatar m93a avatar mazuh avatar mhmdanas avatar mikemcl avatar mkutny avatar ml1nk avatar prayagverma avatar yahsieh avatar zgayjjf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

decimal.js's Issues

Add BigNumber implementations of pi and e

It would be nice to have BigNumber implementations of pi and e in Decimal.js. The constant e is easy, var e = new Decimal(1).exp(). Pi can be calculated with a series expansion. I just tried two relatively simple/short expansions:

The Bailey-Borwein-Plouffe formula

  Decimal.config({precision: 100});

  function pi() {
    // the Bailey-Borwein-Plouffe formula
    // http://stackoverflow.com/questions/4484489/using-basic-arithmetics-for-calculating-pi-with-arbitary-precision
    var p16 = new Decimal(1);
    var pi = new Decimal(0);
    var precision = Decimal.config().precision;

    var one = new Decimal(1);
    var two = new Decimal(2);
    var four = new Decimal(4);
    var k8 = new Decimal(0);

    for (var k = new Decimal(0); k.lte(precision); k = k.plus(one)) {
      // pi += 1/p16 * (4/(8*k + 1) - 2/(8*k + 4) - 1/(8*k + 5) - 1/(8*k+6));
      // p16 *= 16;
      //
      // a little simpler:
      // pi += p16 * (4/(8*k + 1) - 2/(8*k + 4) - 1/(8*k + 5) - 1/(8*k+6));
      // p16 /= 16;

      var f = four.div(k8.plus(1))
          .minus(two.div(k8.plus(4)))
          .minus(one.div(k8.plus(5)))
          .minus(one.div(k8.plus(6)));

      pi = pi.plus(p16.times(f));
      p16 = p16.div(16);
      k8 = k8.plus(8);
    }

    return pi;
  }

  var calculatedPi = pi();

Machin's formula

  Decimal.config({precision: 100});

  // arctan(x) = x - x^3/3 + x^5/5 - x^7/7 + x^9/9 - ...
  //           = x - x^2*x^1/3 + x^2*x^3/5 - x^2*x^5/7 + x^2*x^7/9 - ...
  function arctan(x) {
    var y = x;
    var yPrev = NaN;
    var x2 = x.times(x);
    var num = x;
    var sign = -1;

    for (var k = 3; !y.equals(yPrev); k += 2) {
      num = num.times(x2);

      yPrev = y;
      y = (sign > 0) ? y.plus(num.div(k)) : y.minus(num.div(k));
      sign = -sign;
    }

    return y;
  }

  function pi() {
    // Machin: Pi / 4 = 4 * arctan(1 / 5) - arctan(1 / 239)
    // http://milan.milanovic.org/math/english/pi/machin.html

    // we calculate pi with a few decimal places extra to prevent round off issues
    var DecimalPlus = Decimal.constructor({precision: Decimal.config().precision + 4});
    var pi4th = new DecimalPlus(4).times(arctan(new DecimalPlus(1).div(5)))
        .minus(arctan(new DecimalPlus(1).div(239)));

    // the final pi has the requested number of decimals
    return new Decimal(4).times(pi4th);
  }

  var calculatedPi = pi();

Both work fine. Machin's formula is in the order of 3 times faster than Bailey-Borwein-Plouffe. To calculate pi with 100 digits takes ~10ms, pi with 1000 digits takes ~180ms.

Add a custom decimal separator to toFormat

Hello Mike,
I'm going to use your amazing decimal.js library in one of my projects, but I have had to patch the toFormat method because it's not very useful for i18n: I need to be able to choose a custom decimal separator too (instead of the dot that is forced in the library).
For example, consider some typical formats used in Spain:
"1.234.567,8910"
"1 234 567,8910"

You might want to add the functionality to the vanilla decimal.js library, and I would suggest adding the patched toFormat method to Big.js and BigNumber.js too because it's really useful and small.

I can't open a pull request because I wouldn't know what dependencies to edit (documentation, etc.).

Thanks!

Crypto dependency issue when bundling with browserify or webpack

Decimal.js has a dependency on the crypto library. When bundling decimal.js as part of a larger application using browserify or webpack, a browser compatible version of crypto is bundled with the app by default. This works, but crypto is quite a large dependency.

Looking at the code of decimal.js, the intention is to use native crypto functionality when in the browser, and use the crypto library when in node.js.

I can exclude crypto when bundling my application. That works fine in node.js, but not in the browser via AMD/require.js: decimal.js thinks that we are in a node.js environment because module and module.exports are defined, and tries to load crypto via require rather than using the browsers native crypto implementation (see L3598).

It would be great if this loading of crypto could be rewritten such that the browser environment is correctly detected. Maybe by just checking the ducktype way: first check whether window and window.crypto exist, and if not, fallback to loading via require('crypto'), and if that fails, silently disable the crypto functionality.

Typescript

Hello! Thanks for great library! But typescript definitions in package can be great help!

`random()` has slightly biased distribution

This is a fantastic library! Thanks! One small issue.

The normalization of the exponent done at the end of random() normalizes the exponent but does not do the corresponding shift of the "mantissa digits" (as was done in the line above with rd.shift()).

This means that the numbers produced that have leading zeros will not have a normalized "mantissa" and as a consequece will be biased towards being smaller than they should be.

If normalization is not required than these lines should be removed. Otherwise, we must also shift the mantissa (i.e. rd) to the left by LOG_BASE - k digits after normalizing the exponent.

Decimal.log("115.696") not close to Math.log(115.696)

Decimal 4.0.3

log appears to be way off.

Math.log(115.696)
4.750966061432596

Decimal.log("115.696").toString()
"2.0633183441898021906"

I'd love to get rid of every Math.* call and use Decimal exclusively as I am working on a very high precision application. All the other functions I have used have worked great. Hopefully this can be fixed so I can use it too.

gamma implementation...

Would you consider a PR for a gamma function implementation? I have a Decimal.js gamma function implemented using the Lanczos approximation.

Way to get expanded string of long decimal

I'm trying to figure out a way to get the expanded string representation of a decimal. What happens now:

math.bignumber('92012382910382110000000000000000000929123091.0')
bignum.toString()
=> "9.2012382910382110000000000000000000929123091e+43"

What I'd like:

bignum.toString() // or something like it
=> "92012382910382110000000000000000000929123091.0"

Is there any way to get this?

iOS 10.3 sometimes giving different outputs when given the same inputs

I'm having troubles with this library sometimes providing different calculations on iOS 10.3 (both in Safari and Chrome). An example of a calculation which is sometimes returning different values:

var amount = new Decimal(10);
var taxMultiplier = new Decimal(0.06)
var taxAmount = amount.times(taxMultiplier).dividedBy(taxMultiplier.plus(1));
var taxAmountNumber = taxAmount.toNumber();

Sometimes taxAmountNumber will be 0.5660377358490566 (what I expect - good value) other times it is returning 0.56603760000001 (seems to be losing precision - bad value).

Notes:

  • The issue didn't occur for me on iOS 10.0 when going through reproduction steps in our application. Upon updating to iOS 10.3.2 it started occurring.
  • I have reproduced the issue on 2 different iPads running iOS 10.3.1 and iOS 10.3.2.
  • I can't get the calculations to give different outputs outside of being used in our application so can't give a simple reproduction example. :(
  • I'm currently using Decimal.js 6.0.0 but tried upgrading to 7.2.1 which hasn't resolved the issue.
  • The issue seems to occur somewhat randomly (though I can reproduce it in my application ~3 out of 4 times).
  • Restarting the browser gets us out of the bad state.
  • Putting a breakpoint and stepping into a Decimal.js function (eg. constructor or divide function and then immediately resuming execution) will get us out of the bad state and Decimal.js will return the expected values until we put it back in the bad state.
  • When we get Decimal.js into a bad state we always get the same unexpected value back for the above snippet until we return to a good state.
  • Haven't reproduced the issue in any other browser/OS.
  • We are using a non-modified Decimal.js 6.0.0 and aren't overriding any of the prototype/methods or changing precision/rounding options on the Decimal object.

Rough reproduction steps in our app:

  1. Run the above snippet in the console, we will get the good value over and over again.
  2. Interact with app to get it into a bad state.
  3. Run the above snippet in the console, we will get the bad value over and over again.

If I put a breakpoint in the divide function (immediately before the "return q;" line) I can see a number of local variables are different between when Decimal.js gives me the good value vs. when Decimal.js returns the bad value.

Good value: http://i.imgur.com/FvopYro.png
Bad value: http://i.imgur.com/kjJAirB.png

From all my testing this seems to be an obscure issue with Decimal.js specifically on iOS 10.3 (introduced at some time between iOS 10.0 and iOS 10.3.1 release).

This is currently causing big problems for us as it is resulting in the numbers we present to users being inaccurate and not matching up everywhere. I'm still trying to resolve the issue myself but lack knowledge of Decimal.js internals. If anyone has any thoughts they could share on what could be going on that would be appreciated.

Bugs affecting numbers greater than 2^67

Please take a look at the following:

// 2^67
testA = new Decimal('0b10000000000000000000000000000000000000000000000000000000000000000000');
console.log(testA.toFixed()); // 147573952589676412928
testA = testA.minus(1);
console.log(testA.toFixed()); // 147573952589676412930

testB = Decimal.sub('0b10000000000000000000000000000000000000000000000000000000000000000000', '0b1');
console.log(testB.toFixed()); // 147573952589676412930

// 2^67 - 1
testC = new Decimal('0b1111111111111111111111111111111111111111111111111111111111111111111');
console.log(testC.toFixed()); // 147573952589676412927
testC = testC.plus(1);
console.log(testC.toFixed()); // 147573952589676412930

testD = Decimal.add('0b1111111111111111111111111111111111111111111111111111111111111111111', '0b1');
console.log(testD.toFixed()); // 147573952589676412930

Notice that minus() and Decimal.sub() produces an erroneous result when the minuend is equal to or greater than 2^67 (testA and testB). The methods plus() and add() is also effected (testC and testD).

(tested in Google Chrome 54 and Mozilla Firefox 50 on 64-bit Windows 10)

Read config via `Decimal.config()` not allowed

The function config returns the current config. To just read the config, it would be convenient if we could call the method without argument, like so:

var current = Decimal.config(); // read current config, doesn't work

Right now this is not allowed and you have to provide an empty object like Decimal.config({}).

Loses digits at Decimal construction time

Number.MAX_VALUE has a precise value of 21024 - 2971 =

179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368

This can be demonstrated (with care) by doing a little arithmetic with it:

console.log(Number.MAX_VALUE % 10000) // 8368

However, when I construct a Decimal object from this value, it looks as if most of the decimal digits are discarded.

Decimal.set({precision: 1000, toExpPos: 1000})
console.log(new Decimal(Number.MAX_VALUE).toString())

179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Note that the information is lost at construction time, not at stringification time:

console.log(new Decimal(Number.MAX_VALUE).mod(10000)) // this is 0

The suggested fix is to convert numbers to something like "0b" + Number.MAX_VALUE.toString(2) at Decimal construction time. This retains all the digits, including fractional ones, albeit as binary. Then parse the resulting string.

Weird pow function behavior

pow seems to fail here:

 Testing pow...

 Test number: 1 failed
 -74.25^-81.25
 Expected: -1.0137e-152
 Actual:   NaN
 pr:  500
 rm: HALF_UP

I'm not sure if this is a known limit, so I figured I would let you know.

ReferenceError: "Decimal" is not defined

I am trying to use the following in Code.gs of a Google Apps Script application:

function myFunction(original_value, multiplier) {
  var javascript_value = original_value * multiplier;
  var my_decimal_js_value = new Decimal(original_value).times(new Decimal(multiplier));
....

I am getting the error:

ReferenceError: "Decimal" is not defined

I have tried calling the script in the following ways in index.html:

After jQuery like this:

<?!= include('js_jquery-3.1.0'); ?>
<?!= include('js_decimal.min'); ?>

And in a script tag like this:

<script src='https://cdnjs.cloudflare.com/ajax/libs/decimal.js/7.1.1/decimal.min.js'></script>

The same code is working correctly in a JSFiddle.

Can anyone tell me how to get it working in Code.gs.

Thank You.

Edit: Several jQuery plugins are included and they load fine.

Parsing numbers as strings

I recently encountered the issues below in this wonderful package:

new Decimal('+12'); // Throws an error (because of the +)
new Decimal(' 12 '); // Throws an error (because of the spaces)

Anjo.

Rename Lib to be commonjs compliant

Hello,

I was trying to use Decimal.js within a project which uses commonjs as module resolution.

Unfortunately the ".js" suffix makes the resolver go crazy as it thinks require('decimal.js'); is a require for a file within the folder.

You can read more about the spec here: http://wiki.commonjs.org/wiki/Modules/1.1

1. The "require" function accepts a module identifier. ...
... Module identifiers may not have file-name extensions like ".js".

Weird behavior of mod after cloning the constructor

I encountered some weird behavior in decimal.js v5:

console.log('65 % 40 = ' + new Decimal(65).mod(40));   // 25, correct

var D = Decimal.clone({});  
console.log('65 % 40 = ' + new D(65).mod(40));         // -15, not correct

any idea?

Cosine mutates value...

I belive you have a bug in the cosine function here: https://github.com/MikeMcl/decimal.js/blob/master/decimal.js#L2788 that causes .cos() to mutate the source values. To reproduce:

var Decimal = require("decimal.js");

var x = new Decimal(-5);
console.log(x, x.isNeg());  // prints Decimal {s: -1, e: 0, d: Array[1]} true
x.cos();  // should not alter x
console.log(x, x.isNeg());  // prints Decimal {s: 1, e: 0, d: Array[1]} false

You can see the result here: http://requirebin.com/?gist=f051470dccf8b530f102

isPositive() returns true for zero

I was surprised that isPositive() returns true when the value is zero. I assumed it would be the same as greaterThan(0). Is this behaviour by design? I think it will cause bugs because many people assume positive numbers are > 0.

Proper significant figure calculation

Hi,

Right now, decimal.js strips all trailing fractional zeros. The FAQ quotes a possible problem when trailing zeros are not removed:

x = new BigDecimal("1.0")
y = new BigDecimal("1.1000")
z = x.add(y)                      // 2.1000

x = new BigDecimal("1.20")
y = new BigDecimal("3.45000")
z = x.multiply(y)                 // 4.1400000

While the example does show ambiguity, it does not take into account proper rounding significance arithmetic. For example, the way it should behave is:

x = new BigDecimal("1.0")
y = new BigDecimal("1.1000")
z = x.add(y)                      // 2.1, as the first one has 1 fractional digit while the second one has 4. Rounding to 1 fractional digits.

x = new BigDecimal("1.20")
y = new BigDecimal("3.45000")
z = x.multiply(y)                 // 4.14, as the x has 3 significant figures while the second one has 6. Rounding to 3 fractional digits.

This way, there would be no ambiguity at all.

If proper rounding with trailing zeros is to be implemented, I don't object disabling it by default for compatibility reasons, although I do think disabling it would cause some surprises for newcomers, especially those who saw decimal.js'

precision is specified in terms of significant digits instead of decimal places, and all calculations are rounded to the precision (similar to Python's decimal module) rather than just those involving division.

base85 encoding

@MikeMcl, Wondering if you'll accept a PR adding base85 encoding if I throw it up. I have an interest in saving an extra 10 bytes or so when printing out a large number. It would be nice to offer arbitrary base sizes for those of us with size constraints.

We can use the characters in the zeromq Z85 spec: http://rfc.zeromq.org/spec:32

If you want to throw in the + character we could actually get the encoding up to base87 ($ is part of Z85, but _ isn't). I figure the ordering of characters or adhering to a certain spec isn't that important as long as we retain back compat with your base64 implementation – since you're not adhering to the actual base64 spec at the moment.

Proposed numerals variable would look like this:
NUMERALS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_.-:+=^!/*?&<>()[]{}@%#+'

How to import decimal in typescript project?

How to import decimal in typescript project?

I am trying to do

import Decimal from 'decimal.js/decimal.es6.js';

and it fails with "Cannot find module 'decimal.js/decimal.es6.js'." error even the decimal.js/decimal.es6.js is in npm modules.

x instanceof Decimal not working for me

const Decimal = require('Decimal.js');

let x = new Decimal(12.1231);
console.log(x instanceof Decimal);  // outputs false
console.log(x.constructor.name);  // outputs Decimal

Should this be working?

Don't throw on invalid string

Have you considered returning something on invalid input to the constructor rather than throwing an error? Similar to how parseInt and parseFloat returns NaN on invalid string. Currently the only way to determine if a string is valid input is to catch the error:

function createDecimal (value) {
  try {
    return new Decimal(value);
  } catch (e) {
    return NaN;
  }
}

This would allow something like:

const x = createDecimal(value) || createSomethingElse(value);

Decimal.round confusing

He Michael, great job with this new library! It's even nicer and more complete than bignumber.js.

When switching from bignumber.js to decimal.js, I came across one confusing thing: the behavior of the function round. I understand how the function works and it is well documented, but it's quite counter intuitive.

How about renaming the function toDecimalPlaces to round, and renaming round to toSignificantDigits ?

Bower support

It will be nice if there will be possibility for install decimal.js via bower

0 = 1e-20

In certain cases, adding 1 and -1 equals 1e-20 instead of 0, if the -1 is derived a certain way. If I replace the offending -1 with a new Decimal(-1) it works fine.

Please see this jsfiddle: https://jsfiddle.net/kbyeumff/

`crypto: true` setting doesn't work in latest versions of node.js (v8.2.1)

Just thought I'd point this out, also v8 is becoming the LTS this October so full support for it is ideal.

My Code:

const crypto = require("crypto"), decimal = require("decimal.js");
decimal.set({rounding: decimal.ROUND_HALF_DOWN, minE: -2043, maxE: 2043, toExpNeg: -3, toExpPos: 3, crypto: true});
console.log(new decimal("999e2042").valueOf());

The Error:

/home/ubuntu/workspace/node_modules/decimal.js/decimal.js:4194
            throw Error(cryptoUnavailable);
            ^

Error: [DecimalError] crypto unavailable
    at Function.config (/home/ubuntu/workspace/node_modules/decimal.js/decimal.js:4194:19)
    at Object.<anonymous> (/home/ubuntu/workspace/test.js:2:9)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

TypeError: __WEBPACK_IMPORTED_MODULE_4_decimal_js__ is not a constructor

Hi,

getting the following error,

TypeError: __WEBPACK_IMPORTED_MODULE_4_decimal_js__ is not a constructor

I have installed,

npm install decimal.js --save
npm install --save @types/decimal.js

here is what I have done to get this error

import * as Decimal from 'decimal.js';
let amount = new Decimal(0.00);

using,

@angular/cli: 1.2.0
node: 8.1.2
os: darwin x64
@angular/animations: 4.2.5
@angular/common: 4.2.5
@angular/compiler: 4.2.5
@angular/core: 4.2.5
@angular/forms: 4.2.5
@angular/http: 4.2.5
@angular/material: 2.0.0-beta.6
@angular/platform-browser: 4.2.5
@angular/platform-browser-dynamic: 4.2.5
@angular/router: 4.2.5
@angular/cli: 1.2.0
@angular/compiler-cli: 4.2.5

with "typescript": "~2.3.4"

Compatibility with Karma

When using karma for unit tests Decimal is not added to the global window object. In the tested code you can not use var x = new Decimal(1); .

It seems that this block of code is loading the library on a wrong way for Karma:
// Node and other environments that support module.exports. } else if (typeof module != 'undefined' && module.exports) { module.exports = Decimal.default = Decimal.Decimal = Decimal; }

auto-truncate option?

I'm not able to parse repeating-decimals and it's rather annoying having to use toString():

var test = 0.6666666666666666;
new Decimal( test.toString() );  // works
new Decimal( test );  // breaks

Powers of -1

At about Number.MAX_VALUE, powers of -1 start returning Infinity.

const Decimal = require("decimal.js");
const x = new Decimal("-1");


console.log(x.pow("1").toString());    // "-1"
console.log(x.pow("2").toString());   // "1"
console.log(x.pow("3").toString());   // "-1"
console.log(x.pow("4").toString());   // "1"
console.log(x.pow("5").toString());   // "-1"
console.log(x.pow("100").toString());  // "1"
console.log(x.pow("101").toString());  // "-1"
console.log(x.pow("1e100").toString());  // "1"
console.log(x.pow("1e200").toString()); // "1"
console.log(x.pow("1e305").toString());  // "1"
console.log(x.pow(Number.MAX_VALUE).toString());  // "1"
console.log(x.pow("1e309").toString());  // "Infinity"
console.log(x.pow("1e400").toString()); // "Infinity"
console.log(x.pow("1e800").toString()); // "Infinity"
console.log(x.pow("1e800000").toString());  // "Infinity"

I miss toFormat

Hi, first of all thanks for this awesome library that fixes javascript math.

I tryed upgrading to 5.0, but now toFormat is not a function and I use it a lot. No deprecation warning or anything. The only reference I found is on 5.0 changelog: Removed toFormat. No further explanation :(

Why is that?

How can I format on 5.x?

my config looks like this:

Decimal.config({
  format: {
    decimalSeparator: ',',
    groupSeparator: '.',
    groupSize: 3,
  }
})

By now I will stick with 4.0.2.
Any pointer in the right direction would be appreciated.

string number with prefixed plus gives error

> decimal.add('+2')
Error: [DecimalError] Invalid argument: +2
    at Error (native)
    at parseOther (/home/aviaryan/dev/nodejs/BigEval.js/node_modules/decimal.js/decimal.js:3736:13)
    at new Decimal (/home/aviaryan/dev/nodejs/BigEval.js/node_modules/decimal.js/decimal.js:4432:55)
    at Decimal.P.plus.P.add (/home/aviaryan/dev/nodejs/BigEval.js/node_modules/decimal.js/decimal.js:1514:9)
    at repl:1:3
    at REPLServer.defaultEval (repl.js:252:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:417:12)
    at emitOne (events.js:82:20)

I remember this used to work earlier. Was it discontinued on purpose or Is it a bug.
I vote for handling such cases.

Decimal objects in JSON.stringify()

How should I go about and handle the Decimal objects when outputting as JSON via JSON.stringify?

Right now, I get something like this:

{
  date: "2015-12-04T00:00:00.000Z",
  value: "=13c6A"
},
{
  date: "2015-12-05T00:00:00.000Z",
  value: "=ay:T4"
}

use of constant `1e7` is not linked to `LOG_BASE`

The hard constant 1e7 is used a few times in random() (for example here).

Rather than a constant, this should depend on LOG_BASE as mathpow(10, LOG_BASE)

Also, random will produce a biased distribution if LOG_BASE is ever larger than 9 because of this and this. Thus, we should throw an error if this ever happens (LOG_BASE > 9) rather than silently return a biased distribution.

Error being thrown when taking powers

I'm running into an issue with the following code when taking powers:

const Decimal = require("decimal.js");
Decimal.set({precision: 100});
const baseStr = "0.9999999999999999999999999999999899999999999999994403269002375809806554775739676251993670310626872684";
const expStr = "-1.49181945463118148622657269735650603014891811120124843379694396257337810020127409048127397077199569e+271";

const base = new Decimal(baseStr);
const exp = new Decimal(expStr);

console.log(base.pow(exp).toString());

An error is thrown:

    for (k = d[0]; k >= 10; k /= 10) --i;
              ^

TypeError: Cannot read property '0' of null
    at checkRoundingDigits

any assistance with this would be much appreciated

Accuracy loss

console.log(Decimal.pow(2, 128).div(Decimal.pow(2, 125)).toString())
gives 7.9999999999999999999
(node.js v8.2.1 & 6.9.1)

Weird issue in Ubuntu QML apps

A user of math.js reported some weird behavior when using big numbers (powered by decimal.js). When using decimal.js in an Ubuntu HTML5 app (QML), for some inputs there are digits lost. Here is some example output:

console.log(new Decimal('3.33300000003').toString());  // 3.00000000003   WRONG
console.log(new Decimal('33.3300000003').toString());  // 33.0000000003   WRONG
console.log(new Decimal('33.33000003').toString());    // 33.00000003     WRONG
console.log(new Decimal('33.330003').toString());      // 33.330003       OK

I'm not familiar with QML myself, but installed the SDK and verified this behavior. I'm not sure what JavaScript engine is used but I thought it was Chromium. When loading decimal.js into the QML app, I got a warning that decimal.js could not be loaded as UTF8, but I don't think that is related. I also verified that the problem is in constructing a Decimal, it's not in the toString method (I just looked at the digits in the .c array).

Do you have any clue what could cause this issue?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.