simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

bignumbers.js (1754B)


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