How to compute an exponent in matlab without getting inf?

天大地大妈咪最大 提交于 2019-11-30 05:42:42

问题


The title says it all: I want to calculate an exponent in matlab with big numbers, but I get overflow and it just returns infinity.

>> 100^1000

ans =

   Inf

Last time I checked, 100^1000 is decidedly smaller than infinity :)


回答1:


As Daniel has already pointed out, it's too big a number to be even outputted by MATLAB itself. This number is obtained with realmax for different datatypes. As an alternative to represent/use such huge numbers, you can use the corresponding mantissa and exponent with base-10 representation instead, which is the usual MATLAB representation. The function to get those two is listed here -

function [mantissa, base10_exponent] = base10_mantissa_exponent(base,exponent)

act_exp = exponent*log10(abs(base));
base10_exponent = floor(act_exp);
mantissa = power(10,act_exp - base10_exponent);

if rem(exponent,2)==1 && sign(base)==-1
    mantissa = -mantissa;
end

return;

Few example runs and comparisons with actual MATLAB runs for validation are listed next.

Ex #1

base = -125.343;
exponent = 101;
usual_approach = base^exponent
[mantissa, base10_exponent] = base10_mantissa_exponent(base,exponent)

Output -

usual_approach =
 -8.0930e+211
mantissa =
   -8.0930
base10_exponent =
   211

Ex #2 (problem discussed in the question)

base = 100;
exponent = 1000;

Output -

usual_approach =
   Inf
mantissa =
     1
base10_exponent =
        2000



回答2:


Working with 64bit floating point arithmetic, 100^1000 is inf because it is larger than the largest possible value. If the symbolic math toolbox is available, use vpa or sym to work with large numbers:

sym('100^1000')

or

vpa('100^1000')



回答3:


To deal with large numbers there is also the class High Precision Float, with which the result can be achieved by writing

a = hpf(100);
b = hpf(1000);
c = a^b;

which gives c = 1.e2000. A call to struct(c) provides informations on how the number is internally stored.

struct(c)

ans = 

NumberOfDigits: [64 4]
   DecimalBase: 4
          Base: 10000
       Numeric: 0
          Sign: 1
      Exponent: 2001
        Migits: [1000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]


来源:https://stackoverflow.com/questions/25533237/how-to-compute-an-exponent-in-matlab-without-getting-inf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!