Thread: Floating Point Modulus

  1. #1
    Registered User
    Join Date
    Oct 2011

    Floating Point Modulus

    I'm trying to find the modulus of two floating point numbers. I should be able to use fmodf, but I'm getting seemingly random values when I pass it the numerator as a variable.

    For example,
    alpha = fmodf(31, 7);
    returns 3.000000, which is correct, but
    float theta_demand = 31;
    alpha = fmodf(theta_demand, 7);
    returns 6.000000, which makes no sense.

    Anyone had this problem before?


  2. #2
    Registered User
    Join Date
    Nov 2010
    Long Beach, CA
    Nope. Here's my test program and output:
    #include <stdio.h>
    #include <math.h>
    int main(void)
        float theta = 31;
        float alpha;
        alpha = fmodf(31, 7);
        printf("Using just literals, alpha = %f\n", alpha);
        fmodf(theta, 7);
        printf("Using a variable in the numerator, alpha = %f\n", alpha);
        return 0;
    $ gcc -Wall -o fmod fmod.c -lm
    $ ./fmod
    Using just literals, alpha = 3.000000
    Using a variable in the numerator, alpha = 3.000000
    Can you give us the smallest possible complete program that shows the differing behavior? Also, what OS, compiler, IDE, etc are you using (names and versions)?
    Last edited by anduril462; 10-17-2011 at 10:00 AM.

  3. #3
    Registered User
    Join Date
    Oct 2011
    I tried your code and got the same results as you. I then realised that I'd used theta_demand (the variable name I was passing to fmodf) as a parameter in the function I was writing, and I was initialising it with the value (31) outside it. Stupid mistake really, but thanks for helping me find it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. floating point help!
    By NoobieGecko in forum C Programming
    Replies: 7
    Last Post: 03-09-2008, 02:51 PM
  2. Floating-Point (BCD)
    By zx-1 in forum C Programming
    Replies: 1
    Last Post: 10-15-2004, 01:11 AM
  3. Floating-point modulus
    By Sang-drax in forum C++ Programming
    Replies: 3
    Last Post: 10-01-2002, 08:20 PM
  4. fixed point / floating point
    By confuted in forum Game Programming
    Replies: 4
    Last Post: 08-13-2002, 01:25 PM
  5. Floating point faster than fixed-point
    By VirtualAce in forum A Brief History of
    Replies: 5
    Last Post: 11-08-2001, 11:34 PM