How to compute an exponent in matlab without getting inf?

前端 未结 3 930

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 =
         


        
3条回答
  •  孤独总比滥情好
    2021-01-06 02:29

    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
    

提交回复
热议问题