Matlab vs C++ Double Precision

后端 未结 2 1197
误落风尘
误落风尘 2020-11-28 15:57

I am porting some code from Matlab to C++.

In Matlab

format long
D = 0.689655172413793 (this is 1.0 / 1.45)
E = 2600 / D
// I get E          


        
相关标签:
2条回答
  • 2020-11-28 16:40

    If I understand what you are trying to achieve, using ceil function might help:

    ans = ceil(ans); /* smallest integral value that is not less than ans. */
    // now ans in C++ is also be 3970.
    

    Here is usage reference.

    0 讨论(0)
  • 2020-11-28 16:52

    You got confused by the different ways C++ and MATLAB are printing double values. MATLAB's format long only prints 15 significant digits while C++ prints 17 significant digits. Internally both use the same numbers: IEEE 754 64 bit floating point numbers. To reproduce the C++-behaviour in MATLAB, I defined a anonymous function disp17 which prints numbers with 17 significant digits:

    >> disp17=@(x)(disp(num2str(x,17)))
    
    disp17 = 
    
        @(x)(disp(num2str(x,17)))
    
    >> 1.0 / 1.45
    
    ans =
    
       0.689655172413793
    
    >> disp17(1.0 / 1.45)
    0.68965517241379315
    

    You see the result in MATLAB and C++ is the same, they just print a different number of digits. If you now continue in both programming languages with the same constant, you get the same result.

    >> D = 0.68965517241379315 %17 digits, enough to represent a double.
    
    D =
    
       0.689655172413793
    
    >> ans = 2600 / D %Result looks wrong
    
    ans =
    
         3.770000000000000e+03
    
    >> disp17(2600 / D) %But displaying 17 digits it is the same.
    3769.9999999999995
    

    The background for printing 17 or 15 digits:

    • A double requires 17 significant digits to be stored without precision loss, which is what C prints.
    • For up to 15 digits any number can be converted from string to double to string and results back in the original number, which is what MATLAB does.
    0 讨论(0)
提交回复
热议问题