python - 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 使用单精度而不是双精度,但我不知道为什么,因为我已经定义了sigma
and rho
asdouble precision
并使用了dexp
anddsqrt
而不是exp
and sqrt
。
解决方案
推荐阅读
- c# - 测试 web api 2 时单元测试结果为空对象
- reactjs - 如何启动具有特定页面的反应应用程序?
- html - 如何在 pug 文件/css 中创建圆形图像
- kdb - (q/kdb+) 合并列表中的项目
- dart - 异步方法返回响应后如何导航不同的页面
- java - Android,从特定的 TabBar 项打开活动
- cassandra - 在 Cassandra 上如何启用 LDAP 身份验证
- angular - 如何检查图像链接的角度宽度和高度是否超过 1000
- javascript - 包装 react blackbox 块组件并添加 dom 监听器
- python - 使用 python 请求登录 mega.nz