您的位置:首页 > 其它

Double与0

2015-12-21 22:35 274 查看
#这是关于Double与0之间的一个问题,也许是关于精度的一个问题。

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

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

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

$cat test.c

#include <stdio.h>
#include <math.h>

int main()
{
long double x;
long double step=0.01;
for(x=1.0; x>=-1.0; x-=step) {
printf("%Lf\n",x);
}
return 0;
}


#没有开启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 :

#include <iostream>
#include <fstream>
#include <cmath>

#define MIN_VALUE 1e-8

int main()
{
double x,y,t;
double step=0.01;
bool exit_or_not=false;

std::ofstream outfile;
outfile.open("heart.dat",std::ofstream::out);

for(x=-1.0; x<=1.0+step; x+=step) {
if( fabs(x-0.0)<MIN_VALUE ) {
x=0.0;
}
if( fabs(x-1.0)<MIN_VALUE ) {
x=1.0;
exit_or_not=true;
}

t = 1-x*x;
if(t<0) {
continue;
}
y = sqrt(t)+cbrt(x*x);

outfile << x << " " << y << std::endl;

if(exit_or_not) {
exit_or_not=false;
break;
}
}

for(x=1.0; x>=-1.0-step; x-=step) {
if( fabs(x-0.0)<MIN_VALUE ) {
x=0.0;
}
if( fabs(x+1.0)<MIN_VALUE ) {
x=-1.0;
exit_or_not=true;
}

t = 1-x*x;
if(t<0) {
continue;
}
y = -sqrt(t)+cbrt(x*x);

outfile << x << " " << y << std::endl;

if(exit_or_not) {
exit_or_not=false;
break;
}
}

return true;
}


关于gnuplot作图的细节,再说。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: