Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Mod function 2

Status
Not open for further replies.

Disruptive

Programmer
Mar 8, 2005
40
GB
To save time, I'd love to be able to use the mod function in a calculation, this would be fine if I was using integers. But by using reals or doubles I cannot do this.

The algorithm I am using is something like this

(x + y) mod y. All are defined as integers. Any ideas how to do something like this. I want to avoid using if to save time.

Thanks.
 
Code:
#include <stdio.h>
#include <math.h>

int main(void)
{
   double x = 2.5, y = 1.3, z = [blue]fmod[/blue](x + y, y); /* (x + y) mod y */
   printf("x = %g, y = %g, z = %g\n", x, y, z);
   return 0;
}

/* my output
x = 2.5, y = 1.3, z = 1.2
*/
 
Note that both fmod and % in C only work correctly for positive numbers. The answer is mathematically incorrect for negative numbers. e.g.

-2 % 6 = 2 it should be 4

What they've done is take the positive value and then take the remainder which is easy computationally but incorrect. If you want the mod of a -ve number, you'll have to spin your own.
 
Great, that works a treat. Thanks very much guys for the help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top