0

i am currently working on a matrice math lib in javascript which i have already finished my inverse function for 2x2, 3x3, and for 4x4 matrices using a adjugated cofactor mathod, when i went to multiply my inverse by my original matrice to get the identity matrix to validate my work i noticed a issue, while my diagonal of 1 was correct, where what should have been zeros where not in some places, i checked my work over several times with the help of external calculators and manually checking and i came to the conclusion it wasn't my multiplication.

i then decided to add the numbers for the number in question myself using javascript and the results are very confusing to say the least

4.210526315789474 + 0.6263157894736841 + -0.1578947368421052 + -4.678947368421052

when added in javascript output

8.881784197001252e-16

when added manually or using a calculator output

0.0000000000000009

so i did some more testing and decided to add

-4.836842105263157 + 4.836842105263158

to check if adding just the two sums would output the correct number and sure enough it did....

so my question is, why does

4.210526315789474 + 0.6263157894736841 + -0.1578947368421052 + -4.678947368421052

output the incorrect value, i am truly confused right now, thank you for the help in advanced,

my work environment is in chrome version +63 running js 1.7, all my output was to the developer console using console.log();

daniel
  • 121
  • 9
  • https://stackoverflow.com/questions/588004/is-floating-point-math-broken – epascarello Sep 05 '19 at 13:49
  • See also https://0.30000000000000004.com/ –  Sep 05 '19 at 13:50
  • Possible duplicate of [Why are floating point numbers inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate/21895757) –  Sep 05 '19 at 13:50
  • sorry if this might be a duplicate i searched on google for a while trying to find a question similar on stack and nothing came up, thank you for the links i will look into them (= – daniel Sep 05 '19 at 13:51
  • @daniel If I may make a suggestion, if you learn how to convert a fractional decimal number to binary by hand, it will help to understand this. Some decimal values simply can't be represented accurately in binary. –  Sep 05 '19 at 13:53
  • @Amy thanks for the advice and links i appreciate it – daniel Sep 05 '19 at 13:59
  • @Amy i found that by just rounding in the precision of the floats to around that of a double aka 8 places of precision the math is now correct without error – daniel Sep 05 '19 at 14:02

0 Answers0