简体   繁体   中英

Will Math.pow give the same result on all Node.js platforms?

Will Math.pow return the same result (for the same input) on all Node.js platforms?

I guess that JavaScript arithmetic results are always the same (ie deterministic albeit inexact) because that's defined by the IEEE 754 .

Conversely I guess that the Math function results aren't, necessarily -- especially eg pow where (in theory) different platforms might have different cost/accuracy trade-off in the implementation.

What if I restrict the question though to "all Math.pow results on Node.js " -- eg is the Math library sufficiently similar on all Node.js platform implementations?

So I'm going to talk about floating point arithmetic in general. Since Pow is just a subset it applies to it as well.

Cross platform floating point arithmetic is unfortunately a pain. It is not deterministic even under the assumption that the implementation is the same. One of the issues is that while floating point arithmetic is standardized, the conversion from/to floats is not (and this happens at the very lowest level of NodeJS, I don't count it as a piece of NodeJS' implementation cause it comes from the standard C lib).

Heres a helpful article: https://gafferongames.com/post/floating_point_determinism/

It is possible to get deterministic results for floating calculations across multiple computers provided you use an executable built with the same compiler, run on machines with the same architecture, and perform some platform-specific tricks.

It is incredibly naive to write arbitrary floating point code in C or C++ and expect it to give exactly the same result across different compilers or architectures, or even the same results across debug and release builds.

In your case the application that the text refers to is the NodeJS binary itself. Note that the same version of NodeJS is weaker then the same binary. It's not enough.

So if you have the same binary across the same machines and the code itself is deterministic (how would you know that? NodeJS does lots of stuff under the hood) then your floating point arithmetic has a very good chance to be deterministic as well. But can you guarantee this? Now and in the future? Isn't this hard?

The alternative would be to use some decimal library (eg https://github.com/MikeMcl/decimal.js/ ). Note that it sacrifices performance for correctness. I advise going down that road if performance is not absolutely critical (and it shouldn't be, you use JS after all).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM