JavaScript整数数学结果不正确 [英] JavaScript Integer math incorrect results

查看:180
本文介绍了JavaScript整数数学结果不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想在JS中实现一个简单的RNG。

I am just trying to implement a simple RNG in JS.

正在发生的事情是javascript评估 119106029 * 1103515245 131435318772912110 而不是 131435318772912105 。我们知道这是错误的,因为两个奇数相乘不会给出偶数。

What's happening is javascript evaluates 119106029 * 1103515245 to be 131435318772912110 rather than 131435318772912105. We know it's wrong since two odd numbers multiplied does not give an even number.

任何人都知道怎么了?我只想要一个可靠的可重复RNG,由于这些不正确的值,我无法得到与我同样的C实现相匹配的结果。

Anyone know what's up? I just want a reliable repeatable RNG, and because of these incorrect values I can't get results to match up with my C implementation of the same thing.

推荐答案

根据ECMAScript标准,JavaScript中的所有数字都是(64位IEEE 754)浮点数。

Per the ECMAScript standard, all numbers in JavaScript are (64-bit IEEE 754) floating-point numbers.

但是,所有32位整数都可以精确表示为浮点数。您可以使用适当的按位运算符将结果强制为32位,如下所示:

However all 32-bit integers can be exactly represented as floating-point numbers. You can force a result to 32 bits by using the appropriate bitwise operator, like this:

x = (a * b) >>> 0;  // force to unsigned int32
x = (a * b) | 0;    // force to signed int32

很奇怪,但这是标准。

(顺便说一下,这种舍入行为是最常报告的错误之一 针对Firefox的JavaScript引擎。今年到目前为止已经有3次报道... ...

(Incidentally this rounding behavior is one of the most frequently reported "bugs" against Firefox's JavaScript engine. Looks like it's been reported 3 times so far this year...)

对于JavaScript中的可重现随机数,V8基准使用这个:

As for reproducible random numbers in JavaScript, the V8 benchmark uses this:

// To make the benchmark results predictable, we replace Math.random
// with a 100% deterministic alternative.
Math.random = (function() {
  var seed = 49734321;
  return function() {
    // Robert Jenkins' 32 bit integer hash function.
    seed = ((seed + 0x7ed55d16) + (seed << 12))  & 0xffffffff;
    seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff;
    seed = ((seed + 0x165667b1) + (seed << 5))   & 0xffffffff;
    seed = ((seed + 0xd3a2646c) ^ (seed << 9))   & 0xffffffff;
    seed = ((seed + 0xfd7046c5) + (seed << 3))   & 0xffffffff;
    seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff;
    return (seed & 0xfffffff) / 0x10000000;
  };
})();

这篇关于JavaScript整数数学结果不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆