Why do sin(45) and cos(45) give different results? [duplicate]

匆匆过客 提交于 2019-11-29 12:16:39

I know I will never get a 100% precise value of these numbers, but AT LEAST I was expecting to get the same "unprecise" value of sin and cos of complementary angles.

Why? The are calculated differently, so different floating point errors will occur (and accumulate). What you see is not an error; FP arithmetic isn´t predictable by math laws.

Btw., providing eg. 30 or 100 digits of PI won´t be anything different
if your type can´t hold 30 digits in the first place.

phuclv

regardless of how they are calculated, they are supposed to return the same value

Your expectations are incorrect. In IEEE-754 only basic operators (+-*/) and sqrt are required to be correctly rounded. Trancendental functions like sin, cos, exp... are not required because it's very complex

There is no standard that requires faithful rounding of transcendental functions. IEEE-754 (2008) recommends, but does not require, that these functions be correctly rounded.


Now if you look at your values

                                      ↓
0.70710678118654746 = 0x1.6a09e667f3bccp-1
0.70710678118654757 = 0x1.6a09e667f3bcdp-1
                                      ↑

So they are within 1ulp of each other and is precise enough in double precision

Don't get me wrong, I know I will never get a 100% precise value of these numbers, but AT LEAST I was expecting to get the same "unprecise" value of sin and cos of complementary angles

There's not only a single algorithm to calculate sin and cos. Each will be correct for some set of inputs but incorrect for some others. They also have different memory and time requirements so some can be very fast with higher error, some will require a lot more time and memory but they can achieve much higher accuracy.

Compiler implementations may use different algorithms for those functions so if you need consistent results, use a single carefully designed library across platforms. For example GCC uses MPFR for achieving correctly rounded results regardless of platforms

The GCC middle-end has been integrated with the MPFR library. This allows GCC to evaluate and replace at compile-time calls to built-in math functions having constant arguments with their mathematically equivalent results. In making use of MPFR, GCC can generate correct results regardless of the math library implementation or floating point precision of the host platform. This also allows GCC to generate identical results regardless of whether one compiles in native or cross-compile configurations to a particular target

https://gcc.gnu.org/gcc-4.3/changes.html#mpfropts

How does C compute sin() and other math functions?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!