I hate to be spamming the forums with this, but I've been banging my head at the wall for a few hours now, and I can't really understand what is going on. Here's the full program I'm running:

#include <iostream>
#include "math.h"

int main() {
        std::cout << sin (3.141592653589793) << "\n";
}

The program is returning 1.22461e-16.
Is this simply because I'm not using enough digits of pi? Then why does cos work flawlessly? Any help is greatly appreciated.

It's not about the digits in your pi. It's just the way sin() function works, not much you can do about it. If you really want the 0.0, write an if :P

1.22461e-16 is equal to 0.000000000000000122461, which is pretty close to 0 if you ask me. This is just caused by the precision of the double type and how the data is stored. You could also round the number to remove that problem.

It's in the nature of finite precision.
Theres not much you can do about it.

there a basicly two kinds of datatypes.
1. integral
2. float

integral being, int, char, byte etc
floats being, float, double

integral is always precise, floating values are more obscure

What numerical libraries do is to check for equality within a tolerance like

float one = 0;
float two = 0.0000001

 //wrong
if(one!=two)
  puts("not same");

//right
#define tole 0.000001
if(fabs(one-two)>tole)
  puts("not same")

If you need it depends on your context,
if you just want the value, then you shouldn't care.

But if your program has a branchpoint depending on this value,
you should go the "within tolerance" way.

on a sidenote.
floats are only precise to the 7th or 8th digit,
whereas double are to the 23thd

good luck

May be you still remember (from a school math course) that no fractions which are equal to pi number.
Other post correction: double type provide ~16 decimal digits precision (53 bits of mantissa).

Member Avatar for iamthwee

And you should really include <cmath> instead.

Your output is expected, and here's the result of the same when I tried it on Wolfram's Online Math Engine.

Here: The sin() function prototypes

Ah I see. It's just odd that the cosine of an approximation of pi does return -1, but it's probably just something about the way the math library works.
Anyhow, thanks all!

>It's just odd that the cosine of an approximation of pi does return -1
Exactly!
As usually, math libraries (and FPU hardware) implement high precision (~13-15 decimal digits) polynomial approximations of common math functions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.