Possible Duplicate:
Is JavaScript’s Math broken?
I wrote some simple C# code that runs Python code dynamically (already implemented):
string code = @"100 * 2 + 4 / 3";
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);
int res = source.Execute<int>();
Console.WriteLine(res);
And then I thought about Javascript, and that there are core differences between C# and JS. For example:
In JS:
var t=1.02+1.01 = 2.0300000000000002;
And then I tried this via Jint:
var script = @"
function add( ) {
return 1.02 + 1.01;
};
return add();";
var result = new JintEngine().Run(script);
Console.WriteLine(result);
The result was:
Maybe I don't see the whole picture, but if a programmer on the other side of the world sends me his script file, I (and him) expect the result to be consistent! (Let's ignore the problematic base 2 representation for now, I'm talking about consistency).
If I was mistaken, in what scenario would I use running other code on .Net? (I will have to be very very suspicious for every line of code...)
Am I right ?
var script = @"
function show( )
{
return parseInt('123asd'); //in js it's 123
};
return show();";
var result = new JintEngine().Run(script);
Console.WriteLine(result);
result :
How can I trust a script to yield the same expected result ? ( or am I getting this whole situation wrong...?)
I don't see any "inconsistency". That's just how floating point numbers work!
1) The value - by definition - is seldom "exact"
2) The representation (e.g. from Printing out to a string) can be totally misleading if you try to print out more digits than your value has precision :)
Sample C code
#include <stdio.h>
int
main ()
{
double d = 1.02 + 1.01;
float f = 1.02 + 1.01;
printf ("d=%lf, f=%f\n", d, f);
printf ("d=%25.20lf, f=%25.20f\n", d, f);
return 0;
}
Sample output:
d=2.030000, f=2.030000
d= 2.03000000000000020000, f= 2.02999997138977050000
Excellent article:
Finally, please read this discussion:
The problem is NOT Python, it's NOT C#, it's NOT Javascript.
I assure you :)