简体   繁体   English

Node.js / V8中没有真正的浮点类型?

[英]There is no real float type in Node.js/V8?

I try to store one float value through Buffer in Node.js 我尝试通过Node.js Buffer存储一个float

> f = 3.3
3.3
> var buf = new Buffer(32)
> buf.writeFloatBE(f);
4
> g = buf.readFloatBE();
3.299999952316284

Then I found the stored value g after readFloatBE() is NOT equal to the original f . 然后我发现readFloatBE()之后的存储值g不等于原始f

After further investigation, those two buffer values stored g and f are same. 经过进一步研究,存储gf那两个缓冲值是相同的。

> var buf1 = new Buffer(4); buf1.writeFloatBE(f); buf1
<Buffer 40 53 33 33>
> var buf2 = new Buffer(4); buf2.writeFloatBE(g); buf2
<Buffer 40 53 33 33>

According to this Buffer reading and writing floats , we know the writeDoulbeBE should be used here. 根据这个Buffer读写浮点数 ,我们知道应该在这里使用writeDoulbeBE

> var buf3 = new Buffer(8);
> buf3.writeDoubleBE(f);
8
> h = buf3.readDoubleBE();
3.3
> h === f
true

I want to know why the float type is not used in Node.js or V8 ? 我想知道为什么在Node.jsV8没有使用float类型? Refer to the code from V8 请参阅V8代码

  // Fast primitive setters
  V8_INLINE void Set(bool value);
  V8_INLINE void Set(double i);
  V8_INLINE void Set(int32_t i);
  V8_INLINE void Set(uint32_t i);

It seems there is NO float type in V8 , any reason of this design or am I missing something? 似乎V8没有float类型,这个设计的任何原因还是我错过了什么? In which case, should this function writeFloatBE() be used? 在这种情况下,是否应该使用此函数writeFloatBE()

It seems there is NO float type in V8 似乎V8中没有float类型

Yes, and this is by design: There is no float type in JavaScript either. 是的,这是设计的:JavaScript中也没有float类型。 All numbers are double s as specified by the ECMAScript standard . 所有数字都是ECMAScript标准规定的 double

Your number f is therefore 3.3 with double precision, while g only has float precision. 因此,您的数字fdouble精度的3.3 ,而g只有float精度。 As you can see, that's not the same double as f . 如你所见,这与f The same would happen if you used one of the buf.writeInt… methods, the result after reading it would only be 3 not 3.3 . 如果您使用其中一个buf.writeInt…方法,则会发生同样的情况,读取后的结果只有3而不是3.3

In which case, should the function writeFloatBE() be used? 在这种情况下,应该使用函数writeFloatBE()吗?

Yes, of course it should be used, whenever you want to store numbers with float precision in a buffer. 是的,当然,只要您想在缓冲区中存储具有float精度的数字,就应该使用它。 If you want to store f with full precision, use writeDoubleBE instead. 如果要以完全精度存储f ,请改用writeDoubleBE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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