How to compute an exponent in matlab without getting inf?

前端 未结 3 895

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
    
    0 讨论(0)
  • 2021-01-06 02:45

    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')
    
    0 讨论(0)
  • 2021-01-06 02:52

    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]
    
    0 讨论(0)
提交回复
热议问题