简体   繁体   English

C#Math.pow()返回Infinity?

[英]C# Math.pow( ) return Infinity?

i have problems with Math.pow in c# return infinity for example : 我在c#return infinity中遇到Math.pow问题,例如:

  double a=65;
  double b=331;
  Console.Write(Math.Pow(a,b));
  //but return infinty 

but calculator for my pc not return 65 ^ 331 infinity there are real number return this :1.1866456424809823888425970808655e+600 但我的电脑计算器不返回65 ^ 331无穷大有实数返回此:1.1866456424809823888425970808655e + 600

i use cast to (long) but the result not same windows calculator please i need the variable type is return same window calculator 我使用强制转换为(长)但结果不同于Windows计算器请我需要变量类型返回相同的窗口计算器

double has a limited range ; double 范围有限 ; it cannot store this number. 它无法存储此号码。

Use BigInteger . 使用BigInteger

Math.pow has a limited range it can function with. Math.pow的范围有限,可以使用。 See the MSDN docs for more details. 有关更多详细信息,请参阅MSDN文档

I'm not sure why you're trying to calculate 65^331 . 我不确定你为什么要计算65^331 One work-around would be to use the BigInteger class : 一种解决方法是使用BigInteger类

BigInteger result = new BigInteger(Math.pow(65, 331))

If that doesn't work, there's always good ol' fashioned multiplication: 如果这不起作用,总会有很好的增长:

BigInteger product = 1;
BigInteger a = 65;

for (int i = 0; i < 331; i++) {
    product = BigInteger.Multiply(product, a);
}

This should return the value you want. 这应该返回您想要的值。

If the value is out of range for the type, infinity is returned. 如果该值超出该类型的范围,则返回无穷大。 So, yes, it can return infinity. 所以,是的,它可以返回无穷大。

You should read about IEEE754 floating point to understand the reasons for this. 您应该阅读有关IEEE754浮点的信息,了解其原因。 Basically a number of that magniutude won't 'fit in a machine floating point format (commonly 32 or 64bit). 基本上,一些放大器不适合机器浮点格式(通常为32或64位)。

C++ 32bit vs 64bit floating limit has information on the largest values these machine words will hold, but in short BigInteger is the correct way to handle such large numbers. C ++ 32位与64位浮动限制有关于这些机器字将保持的最大值的信息,但简而言之, BigInteger是处理如此大数字的正确方法。

For example in Python (where integers can be of arbitrary magnitude): 例如在Python中(整数可以是任意大小):

>>>65**331
1186645642480982388842597080865547928975
8025124874226281286044593977851408626647
1648153565617569287290861365843808026786
6910699252797849188956233075264639216543
7504315383537154855617697699290248015932
2796464262757682229990775670822339468164
8291964549985945784276239845489091652362
0705054470856040542942680710474683036796
8985285030088564076789292802170819942388
3788422698744095551323695360171668455050
6467003204582429046323962276940067249678
5724338639806479202984280300919968748839
9063613316621160349502633982277117451890
1573217436770532915029575301234171172274
1482981646754524263087660074234008789062
5L

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

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