Search code examples
javascriptduktape

Exponential calculation bugs in Duktape engine?


I am testing a real-time algorithm adoption with duktape and C language but found that the result return is not always correct. A simple example of passing three floating point numbers to the javascript engine and do some simple exponential calculation returns surprisingly an integer value!

/*
 *  Very simple example program
 */

#include "duktape.h"

#define MAX_FILE_BUFF   65536

void doTest(duk_context *ctx, double x, double y, double z) {

    if (duk_get_global_string(ctx, "GetAlgorithmResult")) {

            duk_push_number(ctx, x);
            duk_push_number(ctx, y);
            duk_push_number(ctx, z);
            duk_call(ctx, 3);

            printf("ALGO(%f,%f,%f) => result = %.6lf\n", x, y, z, duk_get_number(ctx, -1));

            duk_pop(ctx);

    } else {
            printf("did not see the func in duk!\n");
    }

}


int main(int argc, char *argv[]) {

    duk_context *ctx = duk_create_heap_default();

    char js_code_string[MAX_FILE_BUFF];
    FILE *jsfp = fopen("algorithm.js", "r");

    (void) argc; (void) argv;  /* suppress warning */

    if (jsfp != NULL) {

            fread(js_code_string, 1, MAX_FILE_BUFF, jsfp);
            fclose(jsfp);

            duk_eval_string(ctx, js_code_string);
            duk_pop(ctx);  /* pop eval result */

            doTest(ctx, 1.0011, 2.3344, 3.4321);
            doTest(ctx, 3.0011, 4.3344, 7.4321);
            doTest(ctx, 5.0011, 2.3344, 9.4321);
            doTest(ctx, 7.0011, 8.3344, 2.4321);

    } else {
            printf("cannot find the js code to load!!\n");
    }

    duk_destroy_heap(ctx);

    return 0;
}

With an algorithm.js like this:

function GetAlgorithmResult(x, y, z) {

    // this is a testing algorithm calculation in javascript code

    var r = (x ^ y + z);
    return r;
}

Which gives the results:

ALGO(1.001100,2.334400,3.432100) => result = 4.000000
ALGO(3.001100,4.334400,7.432100) => result = 8.000000
ALGO(5.001100,2.334400,9.432100) => result = 14.000000
ALGO(7.001100,8.334400,2.432100) => result = 13.000000

If the algorithm changes to:

function GetAlgorithmResult(x, y, z) {

    // this is a testing algorithm calculation in javascript code

    var r = x * y * z;
    return r;
}

The result is correct:

ALGO(1.001100,2.334400,3.432100) => result = 8.020707
ALGO(3.001100,4.334400,7.432100) => result = 96.676518
ALGO(5.001100,2.334400,9.432100) => result = 110.115691
ALGO(7.001100,8.334400,2.432100) => result = 141.912957

Somebody please Help!!


Solution

  • ^ is a bitwise operator in javascript, not exponent, which it looks like is what you intended. Use Math.pow(x,y) instead of x ^ y.