Rounding floating points
Hello all,
When calculating sin(M_PI) the computer outputs ~-3e-7. Unfortunately, in my program the error grows (it is multiplied by a number on the order of 1e10) into around -208. My question: is there a way to round a float/double to only 3 digits after the decimal point (I do not care for super high accuracy on the sine function but it looks really bad if the final answer is not 0 when it obviously should be)?
Thank you very much in advance,
Ilya
Valmian
Junior Poster in Training
82 posts since Sep 2003
Reputation Points: 13
Solved Threads: 0
short answer -- no, you can't round the internal representation of floats and doubles. That's because many numbers cannot be represented exactly, there are mathametical reasons for that, which is over my head :) but has something to do with powers of 2.
However, you can display them rounded using printf("%3.4f") will print only the first 4 decimals.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
that only rounds to the nearest whole number and discards all deimal places.
#include <iostream>
using namespace std;
#define PI 3.14159265358979323846
int main(int argc, char* argv[])
{
double unrounded = PI;
double rounded = (double)((int)((unrounded*1000)+.5)/1000);
printf("%f\n%f\n", unrounded,rounded);
return 0;
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
BTW, your program's half C, half C++.
Nope. its all c++. Afterall c++ includes all of the standard c functions, turning them into c++ functions with the same name. :eek:
I originally wrote the program using cout instead of printf(), but printf() is easier to code when you need specific number of decimals.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
I had to split the lines to make it work
#include <stdio.h>
#define PI 3.14159265358979323846
int main(int argc, char* argv[])
{
double unrounded = PI;
double rounded = (int)((unrounded*1000)+.5);
rounded /= 1000;
printf("%.8f\n%.8f\n", unrounded,rounded);
return 0;
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343