C sqrt not working properly on floating point numbers below 1 but above 0

448 Views Asked by At

I am trying to create a vector with random dimensions, but with a magnitude of 1. This is what I've come up with (removed the rand() function and replaced it with a number common to both pieces of code.):

  float x = sqrt((4566%100)/100.f);
  float y = sqrt(1.f-x);
  
  printf("%f, %f\n", x, y);
  printf("%f\n", (x*x)+(y*y));

The output is this:

0.812404, 0.433124
0.847596

but when I remove the inverse of the pythagorean theorum (with the code looking a little something like this):

  float x = (4566%100)/100.f;
  float y = 1.f-x;
  printf("%f, %f\n", x, y);
  printf("%f\n", x+y);

the output looks like this:

0.660000, 0.340000
1.000000

Based on the assumption that I'm not insane, the output of the last line of the first piece of code should be 1, and the vector being printed above should be something completely different. I can only assume that the thing that has gone wrong is in the sqrt function. If it is, could someone help me fix it and if it isn't, could someone help me identify my error?

2

There are 2 best solutions below

0
On BEST ANSWER

If, according to the Pythagorean theorem, sqrt(x * x + y * y) = 1, then y is not equal to sqrt(1.f-x). It should be sqrt(1.f-x*x):

  • sqrt(x * x + y * y) = 1
  • (square both sides) => x * x + y * y = 1
  • (subtract x * x from both sides) => y * y = 1 - x * x
  • (calculate the square root of both sides) => y = sqrt(1 - x * x)
0
On

Given the computation for x, this computation of y is incorrect:

  float y = sqrt(1.f-x);

You need to subtract the square of x:

  float y = sqrt(1.f-x*x);

Since x is between 0 and 1, x2 < x, and that will yield a larger (and correct, modulo FP error) value of y.