我正在使用 duktape 和 C 语言测试实时算法采用,但发现结果返回并不总是正确的。将三个浮点数传递给 javascript 引擎并进行一些简单的指数计算的简单示例返回令人惊讶的整数值!
/*
* 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;
}
使用这样的 algorithm.js:
function GetAlgorithmResult(x, y, z) {
// this is a testing algorithm calculation in javascript code
var r = (x ^ y + z);
return r;
}
这给出了结果:
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
如果算法更改为:
function GetAlgorithmResult(x, y, z) {
// this is a testing algorithm calculation in javascript code
var r = x * y * z;
return r;
}
结果是正确的:
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
有人请帮忙!!