简体   繁体   中英

C# Math.pow( ) return Infinity?

i have problems with Math.pow in c# return infinity for example :

  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

i use cast to (long) but the result not same windows calculator please i need the variable type is return same window calculator

double has a limited range ; it cannot store this number.

Use BigInteger .

Math.pow has a limited range it can function with. See the MSDN docs for more details.

I'm not sure why you're trying to calculate 65^331 . One work-around would be to use the BigInteger class :

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. Basically a number of that magniutude won't 'fit in a machine floating point format (commonly 32 or 64bit).

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.

For example in Python (where integers can be of arbitrary magnitude):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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