 # COS and something strange cos results are not the same

Hi,

i have implemented two little programm and in both programms i have this lines

``````#define  PI ((float)3.14159265358979323846264338327950288419716939937510)

float theta = -50.0; //

float phi = 0.0; //just for testing purpose set to 0

float result = cos(theta);
``````

now the result in normal c on cpu is

result_cpu = 0.642787635

and in the cu file calculated on cpu (not in any kernel)

result_gpu = 0.642787576

in both programms i have included the math.h

any idears why this happens? because i need the values calculated with this result for my kernel and i think there should not be any difference between this two values.

cheers

how can i select the math standard cos function in cu file if this is the problem

[/edit]

nobody any idea

All floating point numbers (float, double) are only approximations of real numbers. What you got there are two different approximations, none “correct” in pure mathematical sense, but both good enough for most applications.

– Kuisma

sure but i need the pure c version of cos. to reache the reference results. how could i tell the nvcc to use std math.h cos?

You mix float and double precision in your example. CUDA can only do float precision, not double. If you change the double precision “cos()” to the float precision “cosf()” I guess your results will be more close to each other.

– Kuisma

not strange at all. the way your code is written, the theta in cos(theta)

is first promoted to double, evaluated returning a double result which is

then converted to float.

the precision of float is 2**-23 which is approx 1.2**10-7- Your first six

digits agree, even the first seven, when your round, so your results agree

as good as float can do.

replying to myself: should be 1.2*10**-7.

Furthermore: the PC will evaluate cos in 80 bits, if you use fsincos assembly.

EVEN if you were to evaluate cos as float on two systems, you would have no

guarantee that the results would be bitwise identical. It would depend how the

cos is calculated: Taylor series, Chebyshev polynomial approximation, table lookup,

etc. If you used a series, the result could depend on the order of evaluation due

to rounding errors which you always have.

In old numerical analysis days it was advised, never to test two floats for

equality (e.g. never if (float == 0.) but if (float != 0.)).

You can assume that (float) cos((double)value) will give you the correct 23 bits

of the mantissa for cos, with the error in higher bits, but as I noted already,

your two results agree within 23 bits (the difference of the results as you show