Modulus with double variables

P

Peter Pippinger

Hello NG,

i need to calculate the modulus with double precisson typed variables.

this works well with integers:
w1 = w1 % 360;

but what do i have to do if i want to use w1 as double?

Thanks a lot!
Peter
 
J

Jim Langston

Peter Pippinger said:
Hello NG,

i need to calculate the modulus with double precisson typed variables.

this works well with integers:
w1 = w1 % 360;

but what do i have to do if i want to use w1 as double?

Well, you have the problem that floating point division does not have a
remainder, otherwise it wouldn't be floating point. But, there is still a
solution.

Take for an example
14.5 / 3.5;
The answer is:
4.1428571428571428571428571428571
So what would the remainder be defined as? This would be how many times 3.5
goes into 14.5 wholy. We see it goes 4 times plus a little bit. This is
easy to figure out. Take the answer as an integer. Multiply it by the
original divider. Then subtract this by the original divider.

float a = 14.5;
float b = 3.5;
int result = static_cast<int>( a / b );
float mod = a - static_cast<float>( result ) * b;
 
P

Peter Pippinger

wow! That´s great. I have packed this in a function:

//
---------------------------------------------------------------------
// -- Modulus mit double Variablen
//
---------------------------------------------------------------------
double modulus(double a, double b)
{
int result = static_cast<int>( a / b );
return a - static_cast<double>( result ) * b;
}

Thanks a lot! you are great!
 
E

Eric Jensen

Peter Pippinger said:
Hello NG,

i need to calculate the modulus with double precisson typed variables.

this works well with integers:
w1 = w1 % 360;

but what do i have to do if i want to use w1 as double?

Thanks a lot!
Peter

double fmod ( double x, double y ); // #include <cmath>

double r,x=5.3,y=2;
r = fmod(x,y); // r is not equal to 1.3

//eric
 
A

Alf P. Steinbach

* Peter Pippinger:
i need to calculate the modulus with double precisson typed variables.

this works well with integers:
w1 = w1 % 360;

but what do i have to do if i want to use w1 as double?

Check out round and floor.
 
S

Steve Pope

Jim Langston said:
float a = 14.5;
float b = 3.5;
int result = static_cast<int>( a / b );
float mod = a - static_cast<float>( result ) * b;

I would worry that the static_cast would round to the
nearest integer rather than truncating towards negative
infinity.

Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top