我怎么能解决这个事实,在C ++,sin(M_PI)不是0? [英] How can I work around the fact that in C++, sin(M_PI) is not 0?

查看:629
本文介绍了我怎么能解决这个事实,在C ++,sin(M_PI)不是0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,

  const double Pi = 3.14159265; 
cout<< sin(Pi); // displays:3.58979e-009

它应该显示数字



我理解这是因为Pi是近似的,但是有什么办法我可以有一个值的硬编码到我的程序,将返回0为sin(Pi)? (一个不同的常量可能?)



如果你想知道我想要做什么:我将极性转换为矩形,虽然有一些printf ()技巧我可以打印它为0.00,它仍然不能一致返回体面的值(在某些情况下,我得到-0.00)



需要正弦和余弦的线是:

  x = r * sin 
y = r * cos(theta);

BTW:My Rectangular - > Polar工作正常...它只是Polar - > Rectangular



感谢!



编辑:我正在寻找解决方法,可以打印sin(一些倍数的pi)作为一个好的圆数到控制台(理想情况下没有一千个if语句)

解决方案

每个计算机科学家应该知道的浮点算法(编辑:也链接到评论)是相当硬核的阅读(我不能宣称已经阅读所有的),但它的关键是这是:你永远不会得到完全准确的浮点计算。从文章:

将无限多个实数压缩成有限数量的位需要近似表示。

不要让程序依赖于浮点计算的确切结果 - 始终允许公差范围。 FYI 3.58979e-009约为0.0000000036。这在您选择的任何合理的容差范围内!


In C++,

const double Pi = 3.14159265;
cout << sin(Pi);                          // displays: 3.58979e-009

it SHOULD display the number zero

I understand this is because Pi is being approximated, but is there any way I can have a value of Pi hardcoded into my program that will return 0 for sin(Pi)? (a different constant maybe?)

In case you're wondering what I'm trying to do: I'm converting polar to rectangular, and while there are some printf() tricks I can do to print it as "0.00", it still doesn't consistently return decent values (in some cases I get "-0.00")

The lines that require sin and cosine are:

x = r*sin(theta);
y = r*cos(theta);

BTW: My Rectangular -> Polar is working fine... it's just the Polar -> Rectangular

Thanks!

edit: I'm looking for a workaround so that I can print sin(some multiple of Pi) as a nice round number to the console (ideally without a thousand if-statements)

解决方案

What Every Computer Scientist Should Know About Floating-Point Arithmetic (edit: also got linked in a comment) is pretty hardcore reading (I can't claim to have read all of it), but the crux of it is this: you'll never get perfectly accurate floating point calculations. From the article:

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation.

Don't let your program depend on exact results from floating point calculations - always allow a tolerance range. FYI 3.58979e-009 is about 0.0000000036. That's well within any reasonable tolerance range you choose!

这篇关于我怎么能解决这个事实,在C ++,sin(M_PI)不是0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆