2

I've been assigned to write a program that takes an int or a float in degrees as input and returns the sin and cos of that value with 6 decimal places. But when the input is 90 and 180 I get weird negative zeros, instead of "positive" zeros.

Code:

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

const double PI = 3.14159265;

int main() {
    float x;
    cin >> x;
    x = x * PI / 180;
    cout << fixed;
    cout << setprecision(6) << sin(x);
    cout << ' ' << setprecision(6) << cos(x) << endl;

}

Undesired Input and output:

In:90 Out:1.000000 -0.000000
In:180 Out:-0.000000 -1.000000

I've tried to fix this by multiplying the result of the cos function by -1 when the input is 90 but it still outputs -0.000000.

Solution: As @harold and @user2618142 pointed out, the result of the calculation was negative, so the approximation returned a negative 0.

Álvaro
  • 141
  • 2
  • 14

1 Answers1

3

Let's take cosine near 90 degrees, so near pi/2 radians. In that region, cosine behaves like cos(x) ≈ pi/2 - x.

So the expected value is the difference between half of actual pi (in its full infinite digits precision) and the "half pi" that we gave it as argument. The half pi we gave it as argument cannot actually be the true half pi, since that would have infinite digits. So already it is clear that whatever the result is, it's definitely not exactly zero.

The actual value being computed here is, in steps:

PI = 3.14159265 = 3.141592650000000208621031561051495373249053955078125
90 * PI = 282.74333849999999301871866919100284576416015625
90 * PI / 180 = 1.570796324999999882265910855494439601898193359375
(float)(90 * PI / 180) = 1.57079637050628662109375

Finally, as WolframAlpha will tell us, the difference between pi/2 and that number is about -4.371139000186243... × 10^-8, so negative.

harold
  • 61,398
  • 6
  • 86
  • 164