File I/O 效率 C vs C++ (一)

又一次吃了浮点数的亏 = =

輝夜(tadvent) posted @ 2009年11月12日 04:41 in C/C++ with tags VC gcc double , 3019 阅读
while(step > 0.02){
        if(x+step <= 100.0 &&
            (ttlen = ttl(x+step, y)) < minlength){
            minlength = ttlen;
            x += step;
        } else if(x-step >=0.0 &&
            (ttlen = ttl(x-step, y)) < minlength){
            minlength = ttlen;
            x -= step;
        } else if(y+step <= 100.0 &&
            (ttlen = ttl(x, y+step)) < minlength){
            minlength = ttlen;
            y += step;
        } else if(y-step >= 0.0 &&
            (ttlen = ttl(x, y-step)) < minlength){
            minlength = ttlen;
            y -= step;
        } else break;
    step /= 2.0;
在 x-y 平面上寻找一个对 ttl 函数的极值点。先用 step 为步长寻找,然后步长减半再找,直到满足一定精度为止。
逻辑上过程上都很简单才对,可惜以上代码在 VC2008 运行正确,用 Gcc 却陷入死循环。
调试下发现居然出现了这种情况:在 A 点时发现 B 比 A 小,然后在 B点 发现 C 比 B 小,而在 C点 又发现 A 更小……于是就在这几个点上跳不出来了。
其实以前也看过不少强调处理浮点数比较时要特别注意的地方,但每个地方都特别写一下又很麻烦,而且觉得 double 的精度够高应该不用担心,没想到还是出了问题。VC 里大概对浮点数的比较运算做了特殊处理才没出错,感觉在这种很细节的地方 VC 非常强调安全性,但可能有时候也会觉得多此一举或是担心性能上的影响吧。
总之发现问题所在就好解决了,(ttlen = ttl(x, y+step)) < minlength 改为 (ttlen = ttl(x, y+step)) < minlength - 1e-4 即可。
AP SSC Question Pape 说:
2022年8月18日 13:21

AP SSC Question Paper 2023 Download – BSEAP Board 10th Class New Model Paper 2023 PDF, It is Available that a huge number of candidates will appear in the Andhra Pradesh X Final examination 2023 which is more than the previous year. AP SSC Question Paper 2023 All the students are looking for their AP SSC 10th Class Previous Question Paper 2023 or AP SSC 10th Exam New Model Paper 2023, AP SSC 10th Sample Question Paper 2023, AP SSC 10th Exam Guess Paper 2023. We are informing such students that they get their Secondary Exam 2023 Question Paper from the official website of the BSEAP Board.

Alyssa 说:
2023年1月06日 22:41

Once again, floating-point numbers have caused issues for computer systems. This time, the cbd oil benefits problem was caused by an error in the way that the numbers were being stored. This led to rounding errors that caused the system to crash.

登录 *

loading captcha image...
or Ctrl+Enter