# Floating point math zero

I searched through the forum and could not find a similar topic, so:

I have timed my code and determined that I can use floating point math, however when I attempt to use the standard library:

float sqrt(float);

function it returns “zero” (the actual zero value not random numbers) randomly when my input is at a constant value. I am also recieving similar problems from other floating point trig functions. Can anyone help, or has anyone experienced similar problems?

Here is the actual function that is calling the sqrt function.

void handleDriveJoystick(void) {
signed int prettyJoyX, prettyJoyY;

//take care of the joysticks
prettyJoyX = (signed int)DRIVER_JOY_X - 127;
prettyJoyY = (signed int)DRIVER_JOY_Y - 127;

if (DRIVER_JOY_X == 127 && DRIVER_JOY_Y == 127)
theta = 0.;

else
theta = atan2((float)prettyJoyX, (float)prettyJoyY);

radius = (int) (10.0 * sqrt((float)(prettyJoyXprettyJoyX + prettyJoyYprettyJoyY)));

``````    ...]

``````

The omitted code does not reference radius at any point.

Thank you for any and all help.

At first I suspected that the problem had to do with integer overflow at this step:

(float)(prettyJoyXprettyJoyX + prettyJoyYprettyJoyY)

However, assuming prettyJoyX and prettyJoyY are bounded at +/- 127, this wouldn’t cause an overflow. Obviously, it also would never be negative. If it isn’t the case that those variables are bounded, then it could be possible that you are overflowing, causing the data to wrap around to a negative number and invalidating “sqrt”.

I will continue investigating.

For what values of prettyJoyX and prettyJoyY do you get zero?

One other possibility:

I’m just going on a hunch, but do you get the problem when you are tethered, or only when on radio? Try it both ways. Dropped OI packets could screw up your calculation.

You commented that the problem is occuring with other math functions as well. Are you using any floating point math in an interrupt service routine? If so are you saving the math data context?

Below is exceprt from the C18 users guide:

If an interrupt service routine uses math library functions or calls a function that
returns 24- or 32-bit data, the math data section (which is named MATH_DATA) should
be saved using a save=section(“MATH_DATA”) qualifier on the interrupt pragma
directive. For example:
#pragma interrupt high_interrupt_service_routine save=section(“MATH_DATA”)

If this is not done then an interrupt could be trashing the results of floating point operations in the main line code.