-3

The answer of this function is returned into the main function of the program, and that works fine. The issue is that any value where the cosine should be 0, it turns out to give a weird irrational number (something like 1.30431912*10^-13). So, 90, 450, and so on, all turn out irrational answers. What's the matter?

  float cosineDegrees() {
        string i;
        double iDouble;

        cout << "Give me a number to find the value of degrees in. ";
        getline(cin, i);

        iDouble = stod(i);

        double PI = 3.14159265359;

        float answer = cos((PI/180)*iDouble);

        return answer;


    }
Rocky
  • 47
  • 1
  • 11
  • pi isn't exactly 3.14159265359, is it? – stijn Mar 08 '16 at 08:29
  • 1
    1.30431912*10^-13 is not irrational. It's perfectly rational, but very close to zero. It's as close to zero as you're likely to get. See also [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken). – molbdnilo Mar 08 '16 at 08:41

2 Answers2

3

Floating-point math has finite precision. Your (PI/180)*iDouble value is about 1.30E-13 radian away from 90 degrees.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • So that's as about as precise I can really get things, then? – Rocky Mar 08 '16 at 08:33
  • I think it would help the OP to also present a solution, or an explanation of how to craft one. – stijn Mar 08 '16 at 08:33
  • @stijn: The question appears to ask for an explanation, not a solution, and thast's non-trivial anyway. cos(45) is not going to return √2. – MSalters Mar 08 '16 at 09:10
1

If you lock Pi to a limited precision you can't expect your 'answer' to be more precise. 10^-13 is basically zero in fact, and it's not 'irrational.' Everything is rational in a computer.

involution
  • 11
  • 2