Tuesday, 28 February 2012

Single v Double Floating-point Numbers With Trig Functions in C & C++


The <math.h> library in C has several trig functions depending on the argument passed to the function. For the sine value of an angle, they are:

double sin(double)
float sinf(float)
long double sinl(long double)

 In C++, the <cmath> library recognizes these C functions, but uses the sin function for all data types. The function is overloaded.

Does it make a difference what type of floating number to use? What happens with the functions when different types are passed?

Microsoft implements the floating-point data types as:

float          4 bytes            3.4E +/- 38 (7 digits)
double         8 bytes            1.7E +/- 308 (15 digits)
long double    same as double

Visual C++ doesn’t support the long double.

Attempt #1 – Float v Double

I have an angle in radians: 1.1234567890123456789. Assigning this value to a float or double definitely makes a difference and it should.

float  fAngle = 1.1234567890123456789;
double dAngle = 1.1234567890123456789;

fAngle becomes 1.1234568, 7 digits of precision.
dAngle becomes 1.1234567890123457, 16 digits of precision.
 
Attempt #2 – Sine of Float v Double

float  fAngle = 1.1234567890123456789;
double dAngle = 1.1234567890123456789;

float fSine = 0;
double dSine = 0;

fSine = sin(fAngle);
dSine = sin(dAngle);

fSine becomes 0.90160114.
dSine becomes 0.90160112364986666.
The difference is 0.000000016350134024 or 1/100,000,000 or 1/1E08.

Attempt #3 – sin v sinf Functions

In C, the sin function is used for double numbers and sinf for float.

This code

fSine = sinf(fAngle);

and this code

fSine = sinf(dAngle);

result in the same return value of 0.90160114.

In the second instance, the code converts the double value to a float and returns a float.



No comments:

Post a Comment