UNPKG

1.67 kBJavaScriptView Raw
1// BigNumbers
2
3// load math.js (using node.js)
4const math = require('../index')
5
6// configure the default type of numbers as BigNumbers
7math.config({
8 number: 'BigNumber', // Default type of number:
9 // 'number' (default), 'BigNumber', or 'Fraction'
10 precision: 20 // Number of significant digits for BigNumbers
11})
12
13console.log('round-off errors with numbers')
14print(math.add(0.1, 0.2)) // number, 0.30000000000000004
15print(math.divide(0.3, 0.2)) // number, 1.4999999999999998
16console.log()
17
18console.log('no round-off errors with BigNumbers')
19print(math.add(math.bignumber(0.1), math.bignumber(0.2))) // BigNumber, 0.3
20print(math.divide(math.bignumber(0.3), math.bignumber(0.2))) // BigNumber, 1.5
21console.log()
22
23console.log('create BigNumbers from strings when exceeding the range of a number')
24print(math.bignumber(1.2e+500)) // BigNumber, Infinity WRONG
25print(math.bignumber('1.2e+500')) // BigNumber, 1.2e+500
26console.log()
27
28console.log('BigNumbers still have a limited precision and are no silve bullet')
29const third = math.divide(math.bignumber(1), math.bignumber(3))
30const total = math.add(third, third, third)
31print(total) // BigNumber, 0.99999999999999999999
32console.log()
33
34// one can work conveniently with BigNumbers using the expression parser.
35// note though that BigNumbers are only supported in arithmetic functions
36console.log('use BigNumbers in the expression parser')
37print(math.eval('0.1 + 0.2')) // BigNumber, 0.3
38print(math.eval('0.3 / 0.2')) // BigNumber, 1.5
39console.log()
40
41/**
42 * Helper function to output a value in the console. Value will be formatted.
43 * @param {*} value
44 */
45function print (value) {
46 console.log(math.format(value))
47}