作者yzugsr (Bird)
看板Programming
标题Re: [问题] 基本程式设计概念的问题
时间Mon Jan 21 10:08:38 2008
※ 引述《trickli (哲)》之铭言:
: (1) Rewrite the following pseudo-code if statement expression
: in a more realistic manner assuming that variables a and b are
: of type real:
: if (a = b) then
: ....
threshold = 0.00001 # 误差容许值
if (a > b - threshold) and (a < b + threshold)
: (2) Explain why this is necessary.
: 这题好像是关於两个实数不太可能相等的问题,但不知道该怎麽作答。
: 这是澳洲某大学 2006 年期末考题,请各位高手帮忙。
: 谢谢。
因为浮点数有精确度的限制
float a = 1;
a /= 3;
a *= 3;
if (a==1) print "Yes"; else print "No";
你应该会得到No的答案
因为执行完第二行时 a的数值应该是1/3 写成十进位是0.3333333333....
电脑是用二进位记符点数的,而且有位数的限制
应该会变成0.0101010101.....循环
执行完第三行 a*=3 就变成0.999999999999999999998之类的东西
最後这个数就小於一了
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.124.99.126
1F:推 trickli:谢谢!原因的部分跟我想的差不多 140.122.184.95 01/21 11:31
2F:推 trickli:至於第一部分的答案的确是不错的想法 140.122.184.95 01/21 11:36