首页 > 解决方案 > Fortran 中的不精确计算

问题描述

我发现与 C++、Python 或 Julia 相比,Fortran 在简单的计算中给出了不同的结果。

Fortran 中的以下代码

program array_slice
    implicit none
    double precision :: sigma = 0.30
    double precision :: rho = 0.75
    write(*,*) dexp(dble(3.) * sigma / dsqrt(dble(1.) - rho*rho))
end program array_slice

另存为test.f90,编译使用ifort test.f90 -o test,返回

   3.89881303534984   

但是,以下 C++ 代码

#include <iostream>
#include <iomanip>
#include <cmath>

int main() {
    double sigma = 0.3;
    double rho = 0.75;
    std::cout << std::setprecision(15) << std::exp(3. * sigma / std::sqrt(1. - rho*rho)) << std::endl;
    return 0;
}

另存为testcpp.cpp,编译使用g++ testcpp.cpp -o testcpp,返回

3.89881282454784

同样,Python 3.8.5 中的以下代码

import numpy as np
sigma = 0.3
rho = 0.75
print(np.exp(3 * sigma / np.sqrt(1 - rho**2)))

返回

3.8988128245478393

同样,Julia 1.6.1 中的以下代码

σ = 0.3
ρ = 0.75
println(exp(3. * σ / sqrt(1 - ρ^2)))

返回

3.8988128245478393

以上所有测试均在 64 位 Win10 WSL 中完成。

我猜 Fortran 使用单精度而不是双精度,但我不知道为什么,因为我已经定义了sigmaand rhoasdouble precision并使用了dexpanddsqrt而不是expand sqrt

标签: pythonc++floating-pointfortranjulia

解决方案


推荐阅读