Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restoring the exact angle from std::cos(angle) using std::acos

Is it guaranteed by the C++ standard that angle == std::acos(std::cos(angle)) if angle is in the range [0, Pi], or in other words is it possible to restore the exact original value of angle from the result of std::cos using std::acos given the mentioned range limit?

The marginal cases when angle is infinity or NaN are omitted.

like image 968
plasmacel Avatar asked Oct 19 '25 15:10

plasmacel


2 Answers

Answer by StoryTeller:

The standard cannot make that guarantee, simply because the result of std::cos may not be representable exactly by a double, so you get a truncation error, which will affect the result of std::acos.

like image 84
4 revs, 2 users 71%Lightness Races in Orbit Avatar answered Oct 22 '25 03:10

4 revs, 2 users 71%Lightness Races in Orbit


From cppreference.com:

If no errors occur, [acos returns] the arc cosine of arg (arccos(arg)) in the range [0 ; π]

In degrees, that's 0 to 180, inclusive, corresponding to cosine values 1 down through -1, inclusive.

Outside that range you can't even get an approximate correspondence. Computing the cosine discards information about which angle you had outside of that range. There's no way to get that information back.

How information is discarded:

First, in degrees, cos(x) = cos(K*360 + x), for arbitrary integer K. Secondly, cos(x) = cos(-x). This adds up to an awful lot of angle values that produce the same cosine value.

Also, even though all readers likely know this, but for completeness: since sines are cosines are very irrational numbers, generally not simple fractions, you can't expect exact results except for maybe cosine 1, which corresponds to 0 degrees.

like image 41
Cheers and hth. - Alf Avatar answered Oct 22 '25 04:10

Cheers and hth. - Alf