Click to See Complete Forum and Search --> : duplicating javscript math errors


mikebates
May 7th, 2009, 06:59 PM
I am trying to replicate javascript maths functions in php. I have been successful with everything up to additions.

Here are some examples, I can't see a pattern here that indicates exactly how javascript is screwing it up. Does anyone know **exactly** what javascript is doing?

I assume it's converting the integers into floating points and losing accuracy there, but I don;t know what floating point it's converting into, I also don't see why it would make a difference wha the first figure in a large number is when doing an addition, but apparently it does???

In the examples it's the 1000's and lower that get screwed up.

Example 1, add x20575940379279400 to 13510798882111488, where x is 1 to 9
Results:
134086739261390880
234086739261390880
334086739261390900
434086739261390900
534086739261390900
634086739261390800
734086739261390800
834086739261390800
934086739261390800

Example 2, add x34086739261390900 to 2814749767106560, where x is 1 to 9
Results:
136901489028497460
236901489028497470
336901489028497500
436901489028497500
536901489028497500
636901489028497400
736901489028497400
836901489028497400
936901489028497400

Example 3, add x36901489028497500 to 9895604649984, where x is 1 to 9
Results
136911384633147490
236911384633147500
336911384633147460
436911384633147460
536911384633147460
636911384633147500
736911384633147500
836911384633147500
936911384633147500

Example 4, add x611686018427388000 to 648518346341351400, where x is 1 to 9
Results
2260204364768739300
3260204364768739300
4260204364768739300
5260204364768739000
6260204364768739000
7260204364768739000
8260204364768739000
9260204364768740000
10260204364768740000

PeejAvery
May 8th, 2009, 10:45 AM
This is because the long datatype is not existent in JavaScript. For that, you will have to use an additional library (http://stz-ida.de/html/oss/js_bigdecimal.html.en). Just in case you don't want to go there, the included files are also attached.

<div style="font: 14px monospace;">
<script type="text/javascript" src="mathcontext.js"></script>
<script type="text/javascript" src="bigdecimal.js"></script>
<script type="text/javascript">
for (var i = 1; i <= 9; i++) {
var firstNumber = parseInt(i + "20575940379279400", 10);
var secondNumber = 13510798882111488;
var finalNumber = parseInt(firstNumber, 10) + secondNumber;

var v1 = new BigDecimal(firstNumber.toString());
var v2 = new BigDecimal(secondNumber.toString());
finalNumber = v1.add(v2);

document.write("&nbsp; " + firstNumber + "<br />+&nbsp; " + secondNumber);
document.write("<br />--------------------<br />&nbsp; " + finalNumber)
document.write("<br /><br />");
}
</script>
</div>