Floating Point Modulus

This is a discussion on Floating Point Modulus within the C Programming forums, part of the General Programming Boards category; Hi, I'm trying to find the modulus of two floating point numbers. I should be able to use fmodf, but ...

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    2

    Floating Point Modulus

    Hi,
    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,
    Code:
    alpha = fmodf(31, 7);
    returns 3.000000, which is correct, but
    Code:
    float theta_demand = 31;
    alpha = fmodf(theta_demand, 7);
    returns 6.000000, which makes no sense.

    Anyone had this problem before?

    Thanks,
    Dave

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,444
    Nope. Here's my test program and output:
    Code:
    #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;
    }
    Code:
    $ 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
    Posts
    2
    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 Cprogramming.com
    Replies: 5
    Last Post: 11-08-2001, 10:34 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21