Fortran 与 Matlab 的精度

Precision of Fortran vs that of Matlab

在 Fortran 中,我输出 tanh(1) 的结果并得到值 0.7615941763:

open(unit=2, file='test_digits.txt', ACTION="write")
write(2, '(1000F14.10)')( real(tanh(1.0)))

不过,我现在尝试在 MatLAB 中做同样的事情,结果是 0.761594155955765。第8位有区别

造成这种精度差异的原因是什么?我能以某种方式修复它吗?

Matlab 默认使用双精度,您使用的是单精度浮点数!它们被限制为 7-8 位数字......如果你也使用双精度,你将获得相同的精度:

program test
  write(*,*) 'single precision:', tanh(1.0)
  write(*,*) 'double precision:', tanh(1.0d0)
end program

输出:

 single precision:  0.761594176    
 double precision:  0.76159415595576485