#include <stdio.h>
int main()
{
int i;
const int N = 4;
double a=0, b=0, c=0, d=0;
for (i = 1 ; i <= N ; i++)
{
a += i;
b += i * i;
}
c = a / N;
d = b / N - c * c;
printf("%.0f\n", d);
return 0;
}
Its result is 1, but I don't know exactly why the result is 1. I think c is 3, and N-c*c is -2.25, so d is -13, so I think printing d's result is -13 but the result is 1.
Where does this result comes from?
It is because you are not noticing the algorithm you are choosing for your solution.
the for loop iterates and make the variables like a = 1+2+3+4 and b = 1^2+2^2+3^3+4^4
then a = 10 and b = 30 it makes c=2.5 and d=7.5-2.5^2=1.25 then you choose to print it
with %.0f and you get ONE.
If you want to print float with 2 point precision use %.2f.
After the for loop, a is 10.0 and b is 30.0. Then c is being assigned 10.0 / 4 so c is 2.5. The next line is equivalent to d = (30.0 / 4) - (2.5 * 2.5), hence d is 7.5 - 6.25, i.e. 1.25. Then you trim all decimals by the "%.0f" argument you give to printf() so what remains is a 1. As in, it's the down rounded version of your 1.25.
If you change the the printing line to:
printf("%f\n", d);
Then you'll see all the decimal digits of your specific d.
As in, the .0 after the % and before the f in the format string you gave printf() is what determines the number of decimal digits to print. Any digits beyond that are being rounded.
I'm trying to check if 1/a == 1/b + 1/c in c++.
a, b and c are positive integers and a is between 1 and 10000.
I'm currently getting wrong answers due to floating point precision and I cannot find a way to do this comparison without using floats.
How do I get a correct answer?
I think this will help you:
1/a = 1/b + 1/c
1 = a/b + a/c
1 = (ac + ab)/bc
bc = ac + ab #no longer needs division
Multiply both sides of the equation by a*b*c to get
b*c == a*c + a*b
a(b+c)==b*c
should work just fine :)
When comparing floating point values it's often not practical to look for exact matches because of precision issues. They can foil even the simplest of problems.
double d = sqrt(2);
cout << (d * d) == 2 // false
Instead you often have to test to see if the values are within a certain error margin
fabs((d * d) - 2) < .001 // true
As this is a programming question, I assume you mean int division.
Now, 1/a where a is a positive intteger type is either 0 or 1, and in fact is 1 iff a==1.
We can abuse bool casts as follows:
(a==1) == ((b==1)+(c==1))
and we avoid any and all use of floats.
You could always turn this into a class called fraction. Use the common denominator to convert all 3 variables to the same denominator, add b and c, then compare to a.
This question already has answers here:
round() for float in C++
(23 answers)
Closed 9 years ago.
I have a function which is designed to round a number down to the nearest even number.
double round(double d)
{
floor(d + 0.5);
if(d % 2 == 1)
{
d = d-1;
}
return d;
}
However, this returns the error "expression must have integral or enum type" when I try to compile the code. The error is reported from the same line as the if statement.
Can anyone point me in the right direction?
The % operator is only defined for integers. You wanna use the fmod() function.
Bill is right about a proper implementation of round(double x).
The floor() function returns a double:
double floor (double x);
which is a floating point type, not an 'integral type', like int or char. Instead of calling floor(d + 0.5); which rounds d and discards the result, you'd want something like:
int i = static_cast<int>(floor(d + 0.5));
return floor(d/2 + 0.5) * 2;
Of course doubles are an approximation. For 10^50 you won't get even numbers probably.
floor doesn't work in place, it returns the floor-ed value. Also % applies for integers so you can't re-use d. What you want is:
int i = floor(d + 0.5);
if(i % 2 == 1)
{
i = i-1;
}
return i;
This version will do what you ask, returning an int.
If the parameter d is outside the range of an int, it returns 0 instead.
(maybe you want to throw an OutOfRange exception or something)
int roundDown2Even(double d)
{
return (INT_MIN <= d && d <= INT_MAX)? ((int)d) & ~1 : 0;
}
Where can I find an implementation or library that computes the remainder of an integer Euclidean division, 0 <= r < |n|?
In C++98 and C++03 versions of C++ language the built-in division (bit / and % operators) might be Euclidean and might be non-Euclidean - it is implementation defined. However, most implementations truncate the quotient towards zero, which is unfortunately non-Euclidean.
In most implementations 5 / -3 = -1 and 5 % -3 = -2. In Euclidean division 5 / -3 = -2 and 5 % -3 = 1.
C++11 requires integer division to be non-Euclidean: it requires an implementation that truncates towards zero.
The issue, as you can see, arises with negative numbers only. So, you can easily implement Euclidean division yourself by using operator % and post-correcting negative remainders
int euclidean_remainder(int a, int b)
{
assert(b != 0);
int r = a % b;
return r >= 0 ? r : r + std::abs(b);
}
Try (x%m + m)%m if the result must be positive.
Write your own function around this, or any of the variants, and don't get hung up on a library - you've spent more time asking than you would to just do it. Start your own library (toolbox) for simple functions you need.
It's a simple operator. %.
5 % 4 is 1, etc.
Edit:
As has been pointed out, depending on your implementation this isn't necessarily a euclidean mod.
#define EUCMOD(a, b) (a < 0 ? (((a % b) + b) % b) : (a % b))
I really liked Brandon's answer, but I started having some strange bugs.
After some testing I found that the expansion of the EUCMOD macro was messing with the precedence of operations.
So I'd suggest using it as a function instead of a macro
int eucmod(const int a, const int b)
{
return (a < 0 ? (((a % b) + b) % b) : (a % b));
}
Or adding a few parenthesis
#define EUCMOD(a,b) ((a) < 0 ? ((((a) % (b)) + (b)) % (b)) : ((a) % (b)))
One of my pet hates of C-derived languages (as a mathematician) is that
(-1) % 8 // comes out as -1, and not 7
fmodf(-1,8) // fails similarly
What's the best solution?
C++ allows the possibility of templates and operator overloading, but both of these are murky waters for me. examples gratefully received.
First of all I'd like to note that you cannot even rely on the fact that (-1) % 8 == -1. the only thing you can rely on is that (x / y) * y + ( x % y) == x. However whether or not the remainder is negative is implementation-defined.
Reference: C++03 paragraph 5.6 clause 4:
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
Here it follows a version that handles both negative operands so that the result of the subtraction of the remainder from the divisor can be subtracted from the dividend so it will be floor of the actual division. mod(-1,8) results in 7, while mod(13, -8) is -3.
int mod(int a, int b)
{
if(b < 0) //you can check for b == 0 separately and do what you want
return -mod(-a, -b);
int ret = a % b;
if(ret < 0)
ret+=b;
return ret;
}
Here is a C function that handles positive OR negative integer OR fractional values for BOTH OPERANDS
#include <math.h>
float mod(float a, float N) {return a - N*floor(a/N);} //return in range [0, N)
This is surely the most elegant solution from a mathematical standpoint. However, I'm not sure if it is robust in handling integers. Sometimes floating point errors creep in when converting int -> fp -> int.
I am using this code for non-int s, and a separate function for int.
NOTE: need to trap N = 0!
Tester code:
#include <math.h>
#include <stdio.h>
float mod(float a, float N)
{
float ret = a - N * floor (a / N);
printf("%f.1 mod %f.1 = %f.1 \n", a, N, ret);
return ret;
}
int main (char* argc, char** argv)
{
printf ("fmodf(-10.2, 2.0) = %f.1 == FAIL! \n\n", fmodf(-10.2, 2.0));
float x;
x = mod(10.2f, 2.0f);
x = mod(10.2f, -2.0f);
x = mod(-10.2f, 2.0f);
x = mod(-10.2f, -2.0f);
return 0;
}
(Note: You can compile and run it straight out of CodePad: http://codepad.org/UOgEqAMA)
Output:
fmodf(-10.2, 2.0) = -0.20 == FAIL!
10.2 mod 2.0 = 0.2
10.2 mod -2.0 = -1.8
-10.2 mod 2.0 = 1.8
-10.2 mod -2.0 = -0.2
I have just noticed that Bjarne Stroustrup labels % as the remainder operator, not the modulo operator.
I would bet that this is its formal name in the ANSI C & C++ specifications, and that abuse of terminology has crept in. Does anyone know this for a fact?
But if this is the case then C's fmodf() function (and probably others) are very misleading. they should be labelled fremf(), etc
The simplest general function to find the positive modulo would be this-
It would work on both positive and negative values of x.
int modulo(int x,int N){
return (x % N + N) %N;
}
For integers this is simple. Just do
(((x < 0) ? ((x % N) + N) : x) % N)
where I am supposing that N is positive and representable in the type of x. Your favorite compiler should be able to optimize this out, such that it ends up in just one mod operation in assembler.
The best solution ¹for a mathematician is to use Python.
C++ operator overloading has little to do with it. You can't overload operators for built-in types. What you want is simply a function. Of course you can use C++ templating to implement that function for all relevant types with just 1 piece of code.
The standard C library provides fmod, if I recall the name correctly, for floating point types.
For integers you can define a C++ function template that always returns non-negative remainder (corresponding to Euclidian division) as ...
#include <stdlib.h> // abs
template< class Integer >
auto mod( Integer a, Integer b )
-> Integer
{
Integer const r = a%b;
return (r < 0? r + abs( b ) : r);
}
... and just write mod(a, b) instead of a%b.
Here the type Integer needs to be a signed integer type.
If you want the common math behavior where the sign of the remainder is the same as the sign of the divisor, then you can do e.g.
template< class Integer >
auto floor_div( Integer const a, Integer const b )
-> Integer
{
bool const a_is_negative = (a < 0);
bool const b_is_negative = (b < 0);
bool const change_sign = (a_is_negative != b_is_negative);
Integer const abs_b = abs( b );
Integer const abs_a_plus = abs( a ) + (change_sign? abs_b - 1 : 0);
Integer const quot = abs_a_plus / abs_b;
return (change_sign? -quot : quot);
}
template< class Integer >
auto floor_mod( Integer const a, Integer const b )
-> Integer
{ return a - b*floor_div( a, b ); }
… with the same constraint on Integer, that it's a signed type.
¹ Because Python's integer division rounds towards negative infinity.
Here's a new answer to an old question, based on this Microsoft Research paper and references therein.
Note that from C11 and C++11 onwards, the semantics of div has become truncation towards zero (see [expr.mul]/4). Furthermore, for D divided by d, C++11 guarantees the following about the quotient qT and remainder rT
auto const qT = D / d;
auto const rT = D % d;
assert(D == d * qT + rT);
assert(abs(rT) < abs(d));
assert(signum(rT) == signum(D) || rT == 0);
where signum maps to -1, 0, +1, depending on whether its argument is <, ==, > than 0 (see this Q&A for source code).
With truncated division, the sign of the remainder is equal to the sign of the dividend D, i.e. -1 % 8 == -1. C++11 also provides a std::div function that returns a struct with members quot and rem according to truncated division.
There are other definitions possible, e.g. so-called floored division can be defined in terms of the builtin truncated division
auto const I = signum(rT) == -signum(d) ? 1 : 0;
auto const qF = qT - I;
auto const rF = rT + I * d;
assert(D == d * qF + rF);
assert(abs(rF) < abs(d));
assert(signum(rF) == signum(d));
With floored division, the sign of the remainder is equal to the sign of the divisor d. In languages such as Haskell and Oberon, there are builtin operators for floored division. In C++, you'd need to write a function using the above definitions.
Yet another way is Euclidean division, which can also be defined in terms of the builtin truncated division
auto const I = rT >= 0 ? 0 : (d > 0 ? 1 : -1);
auto const qE = qT - I;
auto const rE = rT + I * d;
assert(D == d * qE + rE);
assert(abs(rE) < abs(d));
assert(signum(rE) >= 0);
With Euclidean division, the sign of the remainder is always non-negative.
Oh, I hate % design for this too....
You may convert dividend to unsigned in a way like:
unsigned int offset = (-INT_MIN) - (-INT_MIN)%divider
result = (offset + dividend) % divider
where offset is closest to (-INT_MIN) multiple of module, so adding and subtracting it will not change modulo. Note that it have unsigned type and result will be integer. Unfortunately it cannot correctly convert values INT_MIN...(-offset-1) as they cause arifmetic overflow. But this method have advandage of only single additional arithmetic per operation (and no conditionals) when working with constant divider, so it is usable in DSP-like applications.
There's special case, where divider is 2N (integer power of two), for which modulo can be calculated using simple arithmetic and bitwise logic as
dividend&(divider-1)
for example
x mod 2 = x & 1
x mod 4 = x & 3
x mod 8 = x & 7
x mod 16 = x & 15
More common and less tricky way is to get modulo using this function (works only with positive divider):
int mod(int x, int y) {
int r = x%y;
return r<0?r+y:r;
}
This just correct result if it is negative.
Also you may trick:
(p%q + q)%q
It is very short but use two %-s which are commonly slow.
I believe another solution to this problem would be use to variables of type long instead of int.
I was just working on some code where the % operator was returning a negative value which caused some issues (for generating uniform random variables on [0,1] you don't really want negative numbers :) ), but after switching the variables to type long, everything was running smoothly and the results matched the ones I was getting when running the same code in python (important for me as I wanted to be able to generate the same "random" numbers across several platforms.
For a solution that uses no branches and only 1 mod, you can do the following
// Works for other sizes too,
// assuming you change 63 to the appropriate value
int64_t mod(int64_t x, int64_t div) {
return (x % div) + (((x >> 63) ^ (div >> 63)) & div);
}
/* Warning: macro mod evaluates its arguments' side effects multiple times. */
#define mod(r,m) (((r) % (m)) + ((r)<0)?(m):0)
... or just get used to getting any representative for the equivalence class.
Example template for C++
template< class T >
T mod( T a, T b )
{
T const r = a%b;
return ((r!=0)&&((r^b)<0) ? r + b : r);
}
With this template, the returned remainder will be zero or have the same sign as the divisor (denominator) (the equivalent of rounding towards negative infinity), instead of the C++ behavior of the remainder being zero or having the same sign as the dividend (numerator) (the equivalent of rounding towards zero).
define MOD(a, b) ((((a)%(b))+(b))%(b))
unsigned mod(int a, unsigned b) {
return (a >= 0 ? a % b : b - (-a) % b);
}
This solution (for use when mod is positive) avoids taking negative divide or remainder operations all together:
int core_modulus(int val, int mod)
{
if(val>=0)
return val % mod;
else
return val + mod * ((mod - val - 1)/mod);
}
I would do:
((-1)+8) % 8
This adds the latter number to the first before doing the modulo giving 7 as desired. This should work for any number down to -8. For -9 add 2*8.