mathjs
mathjs copied to clipboard
Why are my results showing differently in the console ?
eg: math.number(math.multiply(math.bignumber(Number(4.001)), math.bignumber(Number(0.000001)))) result: 0.000004001 this ok !
eg: math.number(math.multiply(math.bignumber(Number(4.1)), math.bignumber(Number(0.00000001)))) result: 4.1e-8 why ?
How are you getting the strings you are showing? Both values are correct numerically; the difference is just about a threshold where the output is switching to scientific notation. So it all depends on whether you are converting to the representations you show using some specific function, or just implicitly (say by showing the value in the console or something). If you use math.format to produce string representations of numeric values, you can control this sort of thing explicitly.
Right, I suspected you might just be showing the values in the console. All that's going on here is that for sufficiently small or large numeric values, the console chooses scientific rather than decimal notation to display the value of a number
entity. The actual numeric values are both correct. In other words, 4.1e-8 is just another representation of 0.000000041, and the internal floating-point numeric representation is identical and is the correct value. So there doesn't seem to be any bug; if there is some difficulty that the console switching to scientific notation for small results is causing you, you can explicitly convert the numeric values to strings with math.format and have complete control over what notation is used. Unless there's any other specific problem you are having in the use of the results of these calculations, I will close this issue tomorrow. Thanks for your interest in msthjs.
Thank you very much.
is that correct?
The JavaScript number
type is a double-precision 64-bit binary format IEEE 754 floating-point number. As with any computational representation, there are limits to its precision, and you are hitting up against those limits at the end of your examples. For some more discussion of this specific to JavaScript, see for example https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number.
If you need more precision for your application, mathjs also offers a BigNumber type. Hope this helps.