Question

I am developing a translator that converts JavaScript source into a target language. I am trying to implement JavaScript's Math object in the target language.

If there is a JavaScript implementation of the "Math" object, I can use the translator to obtain the equivalent code in the target language.

I am looking for something like this:

var Math = {
    pow: function(...) {...}
    exp: function(...) {...}
    /* other methods of Math */
}

Is there such an implementation that is available ? This would help me avoid manually writing the Math object's code in the target language.

Was it helpful?

Solution

The V8 implementation of math.js might provide you with some guidance, but of course it's riddled with placeholders for native function calls. You would have to be able to replace things like %Math_floor(x) with the appropriate standard library based function call in the target language.

http://code.google.com/p/v8/source/browse/branches/bleeding_edge/src/math.js?spec=svn10758&r=10758

OTHER TIPS

This is from the official ecmascript-262 specification:

NOTE The behaviour of the functions acos, asin, atan, atan2, cos, exp, log, pow, sin, sqrt, and tan is not precisely specified here except to require specific results for certain argument values that represent boundary cases of interest. For other argument values, these functions are intended to compute approximations to the results of familiar mathematical functions, but some latitude is allowed in the choice of approximation algorithms. The general intent is that an implementer should be able to use the same mathematical library for ECMAScript on a given hardware platform that is available to C programmers on that platform.

Although the choice of algorithms is left to the implementation, it is recommended (but not specified by this standard) that implementations use the approximation algorithms for IEEE 754 arithmetic contained in fdlibm, the freely distributable mathematical library from Sun Microsystems (http://www.netlib.org/fdlibm).

Objects you need are:

Math.exp(x) // Returns the value of Ex

Math.pow(x,y)   // Returns the value of x to the power of y

Other than these there are more which will help you that you will be needed in java. Those are

Math.PI         // returns PI
Math.random();              // returns a random number
Math.max(0, 150, 30, 20, -8, -200);      // returns 150
Math.min(0, 150, 30, 20, -8, -200);      // returns -200
Math.round(4.7);            // returns 5
Math.round(4.4);            // returns 4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top