C#system.math.pow和SQL-Server Pow函数中的问题 [英] Issue in C# system.math.pow and SQL-Server Pow function
问题描述
HI,
当我们使用system.math.pow函数时,我们面临一个问题.最多2个POW 56,其工作状况良好.我将结果与sql server POW(2.0,56)比较.
从57岁的Pow开始,当与c#和Sql Server结果相适应时,我们在C#和Sql Server中得到了不同的值
示例:
C#
(long)system.math.pow(2,57)
结果-144115188075855872
SQL Server
选择cast(POW(2.0,57)as bigint)
结果-144115188075855870
问候,
Senthil S
We are facing a problem when we use system.math.pow function. Upto 2 POW 56 its working fine. I am comparing the result with sql server POW(2.0,56).
From Pow of 57 onwards,when comaparing c# and Sql Server result we are getting different values in C# and Sql Server
Example:
C#
(long)system.math.pow(2,57)
Result - 144115188075855872
SQL Server
Select cast(POW(2.0,57) as bigint)
Result - 144115188075855870
Regards,
Senthil S
推荐答案
只有当它是整数值时,您才能确定正确的结果.类型System.UInt64
足够大,仅因为57< c0; 64,但不是System.UInt32
(57> 32).
对2的幂使用Pow
函数只是愚蠢的.您需要使用<<向左移动1.运算符,但是对于System.UInt64
来说却不是那么容易,因为仅为int
定义了该运算符.您可以使用System.BitConverter
类非常简单地执行此操作,请参见:
http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx [^ ].
以下是获得确切答案的方法:
You can be sure in a right result only if this is integer value. The typeSystem.UInt64
is big enough, just because 57 < 64, but notSystem.UInt32
(57 > 32).
UsingPow
function for powers of 2 is just silly. You need to shift 1 to the left using << operator, but forSystem.UInt64
this is not so easy because this operator is only defined forint
. You can do it very simply using the classSystem.BitConverter
, please see:
http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx[^].
Here is how to get an exact answer:
static System.UInt64 PowerOfTwo(byte power) {
byte[] bytes = new byte[sizeof(System.UInt64)];
int bitShift = power % 8;
int byteIndex = power / 8;
bytes[byteIndex] = (byte)(1 << bitShift);
return System.BitConverter.ToUInt64(bytes, 0);
}
测试中……答案是144115188075855872;您的C#结果正确,SQL Server是骗子!
如果需要更大的值,则唯一的机会就是类型System.Numerics.BigInteger
;请参阅:
http://msdn.microsoft.com/en-us/library/system.numerics. biginteger.aspx [ ^ ].
Testing… the answer is 144115188075855872; your C# result was correct, SQL Server is a liar!
If you need bigger values, your only chance is the type System.Numerics.BigInteger
; please see:
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx[^].
如果它们不同,则它们也不同.它们在两个地方进行计算.您坐下来确定哪个是正确的吗?
If they are different, then they are different. They are being calculated in two places. Have you sat down to work out which is correct ?
这篇关于C#system.math.pow和SQL-Server Pow函数中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!