将Double转换为Numerics.BigInteger时的数字更改 [英] Number changes when converting Double to Numerics.BigInteger
问题描述
使用System.Numerics;
double doubleNumber = Math.Pow(1000,99); // = 1.0E + 297
BigInteger bigBase =(BigInteger)bigNumber; // = 1000000000000000017652801462756379714374878780719864776839443139119744823869255243069012222883470359078822072829219411228534934402712624705615450492327979456500795456339201761949451160807447294527656222743617592048849967890105831362861792425329827928397252374398383022243308510390698430058459037696
<强>为什么是的BigInteger
值不仅仅是1卡吉(1,000,其次是一个袋子0)?
BigInteger的实现使用大量的位移,所以当你将一个double转换成一个BigInteger时,双重表示有一个有限的位(双位为64位),所以并不是所有的位都准确地表示这个值。 p>
而不是使用Math.Pow,您应该使用
var bigBase = BigInteger.Pow(1000,99);
另外,显式地将数字类型转换为BigInteger与使用BigInteger构造函数相同: p>
var bigBase =(BigInteger)doubleNumber;
相当于:
var bigBase = new BigInteger(doubleNumber);
using System.Numerics;
double doubleNumber = Math.Pow(1000, 99); // = 1.0E+297
BigInteger bigBase = (BigInteger)bigNumber; // = 1000000000000000017652801462756379714374878780719864776839443139119744823869255243069012222883470359078822072829219411228534934402712624705615450492327979456500795456339201761949451160807447294527656222743617592048849967890105831362861792425329827928397252374398383022243308510390698430058459037696
Why is the BigInteger
value not just 1 kagillion (1,000 followed by a bagillion 0's)?
The implementation of BigInteger uses a lot of bit shifting, so when you convert a double to a BigInteger, the double representation has a finite set of bits (64 bits in for a double), so not all the bits are there to accurately represent the value.
Instead of using Math.Pow, you should be using
var bigBase = BigInteger.Pow(1000, 99);
Also, explicitly casting a numeric type to a BigInteger is the same as using the BigInteger constructor:
var bigBase = (BigInteger)doubleNumber;
Is equivalent to:
var bigBase = new BigInteger(doubleNumber);
这篇关于将Double转换为Numerics.BigInteger时的数字更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!