Double与0

#这是关于Double与0之间的一个问题,也许是关于精度的一个问题。

#是无心知道的。具体如下:

 

#有没有开启c99会有这么大的区别吗?

#不知道这个算什么,但是很心疼。

$cat test.c

 1 #include <stdio.h>
 2 #include <math.h>
 3 
 4 int main()
 5 {
 6     long double x;
 7     long double step=0.01;
 8     for(x=1.0; x>=-1.0; x-=step) {
 9         printf("%Lf\n",x);
10     }
11     return 0;
12 }

 

#没有开启c99:

$gcc test.c 
$./a.out
......此处略出许多行
-0.950000
-0.960000
-0.970000
-0.980000
-0.990000

####注意最后一行,可不是 -1.0哦!!!

 

#然后开启c99:

$gcc -std=c99 test.c
$./a.out
......此处略出许多行
-0.950000
-0.960000
-0.970000
-0.980000
-0.990000
-1.000000

####注意最后一行,输出正确哦哦哦~!!!

 

 

###后问百度,引申出另一个问题,浮点数的零其实不是零。

所以浮点数的比较不能单纯的 =0 或者 =-1.0。

应该设置一个精度,在此精度范围内,可以理解为相等。

So......

我写了一个输出心形的x、y坐标数据的程序,然后用gnuplot画图。

所以,详见 heart.cpp : 

 1 #include <iostream>
 2 #include <fstream>
 3 #include <cmath>
 4 
 5 #define MIN_VALUE 1e-8
 6 
 7 int main()
 8 {
 9     double x,y,t;
10     double step=0.01;
11     bool exit_or_not=false;
12     
13     std::ofstream outfile;
14     outfile.open("heart.dat",std::ofstream::out);
15     
16     for(x=-1.0; x<=1.0+step; x+=step) {
17         if( fabs(x-0.0)<MIN_VALUE ) {
18             x=0.0;
19         }
20         if( fabs(x-1.0)<MIN_VALUE ) {
21             x=1.0;
22             exit_or_not=true;
23         }
24         
25         t = 1-x*x;
26         if(t<0) {
27             continue;
28         }
29         y = sqrt(t)+cbrt(x*x);
30         
31         outfile << x << " " << y << std::endl;
32         
33         if(exit_or_not) {
34             exit_or_not=false;
35             break;
36         }
37     }
38     
39     for(x=1.0; x>=-1.0-step; x-=step) {
40         if( fabs(x-0.0)<MIN_VALUE ) {
41             x=0.0;
42         }
43         if( fabs(x+1.0)<MIN_VALUE ) {
44             x=-1.0;
45             exit_or_not=true;
46         }
47         
48         t = 1-x*x;
49         if(t<0) {
50             continue;
51         }
52         y = -sqrt(t)+cbrt(x*x);
53         
54         outfile << x << " " << y << std::endl;
55         
56         if(exit_or_not) {
57             exit_or_not=false;
58             break;
59         }
60     }    
61     
62         
63     return true;
64 }

关于gnuplot作图的细节,再说。

 

转载于:https://www.cnblogs.com/qydw000/p/5065107.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值