JavaScript and Dealing with Floating Point Determinism

自闭症网瘾萝莉.ら 提交于 2021-01-27 05:39:17

问题


I'm looking to build a browser multiplayer game using rollback netcode that runs a deterministic simulation on the clients. I prototyped the netcode in Flash already before I ran into the floating point roadblock.

Basically, from what I understand, integer math in Flash is done by casting ints to Numbers, doing the math, then casting back to int. It's faster apparently, but it means that there's no chance of deterministic math across different computer architectures.

Before I dump all my eggs into the JavaScript basket then, I'd like to ask a few questions.

  1. Is there true integer arithmetic on all major browsers in JavaScript? Or do some browsers do the Flash thing and cast to floats/doubles to do the math before casting back to int?

  2. Does something like BigDecimal or BigNum work for deterministic math across different computer architectures? I don't mind some performance loss as long as it's within reason. If not, is there some JavaScript fixed point library out there that solves my problem?

  3. This is a long shot, but is there a HTML5 2D game engine that has deterministic math for stuff like x/y positions and collisions? The list of game engines is overwhelming to say the least. I'm uneasy about building a deterministic cross browser compatible engine from scratch, but that might be what I have to do.

NOTE: Edited from HTML5 to JS as per responses. Apologies for my lack of knowledge.


回答1:


This is a Javascript issue - not an HTML5 one.

All Javascript math is done using IEEE754 floating point double values - there are no "ints".

Although IEEE754 requires (AFAIK) a specific answer for each operation for any given input, you should be aware that JS interpreters are potentially free to optimise expressions, loops, etc, such that the floating point operations don't actually execute in the order you expect.

Over the course of a program this may result in different answers being produced on different browsers.



来源:https://stackoverflow.com/questions/11493279/javascript-and-dealing-with-floating-point-determinism

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!