Math discrepancy between c# and shader code

Hi, I’ve got the following shader code for hashing a value:

[Shader]
float hash( float n )
{
float v = sin(n) * 43758.5453123;
return v - floor(v); // I realise I could use ‘frac’ here, but I wanted to see if a different result would come out, it didn’t.
}

BUT I need to do the same in C#, but the result do not return the same:-

[C#]
float Hash(float n)
{
float v = Mathf.Sin(n) * 43758.5453123f;
return v - Mathf.Floor(v);
}

The result are not even close! Which is weird, I’m guess it’s a precision thing. At least as a sanity check should these different routines return the same? If so, how do I match the precision, if that’s what’s happening?
Thanks.

As far as I know, the sin function is approximated by its taylor series on graphics cards. Considering that you are multiplying with a fairly high number and then taking the fractional part, the difference in outcome can indeed be huge.

Since sin is not the cheapest function, I generally use the vertex or object position as the hash value.

float hash(float3 position) {
	return frac(dot(position, float3(134.57, 98.71, 153.94)));
}

Since you are using 32 bit floating point numbers in both cases, this should come to the same value on current day desktop gpu’s. Mobile devices might not implement 32 bit floating point numbers fully, so you can still expect differences there.

Edit: I see other reports of sin being implemented on the gpu by piecewise linear approximations. In any case the sin function is not likely to be implemented 100% correctly on a gpu.

Thank-you for informative answer, that’s interesting to know. I had written the code before, outside unity in GLSL, and it worked OK but I hadn’t tested DirectX, which is giving me grief here I believe.
Your code doesn’t give a random enough result for my purposes (Perlin noise, and yes I do want to make my own! :slight_smile: ), so I’m going to use a random texture and pick values out of that. It may be a bit slower but at least I’ll know the values will be consistent. I’m not interested in mobile platforms ATM.
Thanks again,
Dave H.