Octave 中的 Rem 函数显示错误的结果

计算科学 matlab 八度
2021-12-10 14:23:10

我正在尝试编写一个 if 语句,在运行某些命令之前检查 2 个数字是否可整除。问题是,rem 函数对某些数字给出了一些错误的结果(2 绝对可以被 0.5、0.4、0.2 和 0.1 整除,但函数另有说明)。错误的再现发布在下面

t=2
h=1

while h>0
if rem(t,h)==0
  disp ('divisible')
else
  disp('non divisible')
endif
  h-=0.1
endwhile

命令 indow 中的结果是

>> t =  2
h =  1
divisible
h =  0.90000
non divisible
h =  0.80000
non divisible
h =  0.70000
non divisible
h =  0.60000
non divisible
h =  0.50000
non divisible
h =  0.40000
non divisible
h =  0.30000
non divisible
h =  0.20000
non divisible
h =  0.10000
non divisible
h =    1.3878e-16
divisible
h = -0.100000

非常感谢任何解决方案

代码结果

1个回答

0.1在双精度算术中不能完全表示,它将被四舍五入。的双精度表示0.1

00111111 10111001 10011001 10011001 10011001 10011001 10011001 10011010,

这是如您所见,如果您通过反复从中减去“,只是近似地。因此,rem 函数不返回整除也就不足为奇了。如果你尝试,你会看到它返回“整除”,因为 2 的许多幂都可以用双精度精确表示。0.100000000000000005551115123126h0.10.10.20.40.5rem(2,0.5)