Why is the same both (5 % 2) and (-5 % 2) in Python - python-2.7

I have guessed 5 % 2 is 1 , -5 % 2 is -1
But, In Python, I get the same result.
I think it's not math problem.
>>> -5 % 2
1 ( I think this should be -1 )
>>> 5 % 2
1
>>> -7 % 6
5 ( I think this should be -1 )
>>> 7 % 6
1

Why? Because the modulo operator is defined that way in python.
The documentation states:
The modulo operator always yields a result with the same sign as its
second operand (or zero); [...]
And:
The function math.fmod() returns a result whose sign matches the
sign of the first argument instead, [...] Which approach is more
appropriate depends on the application.

You can look at the % operation in at least a couple of different ways. One important point of view is that m % n finds the element of Z[n] which is congruent to m, where Z[n] is an algebraic representation of the integers restricted to 0, 1, 2, ..., n, called the ring of integers modulo n. Note that all integers, positive, negative, and 0, are congruent to some element 0, 1, 2, ..., n in Z[n].
This ring (that is, this set plus certain operations on it) has many well-known and useful properties. For that reason, it's often advantageous to try to cast a problem in a form that leads to Z[n], where it may be easier to work. This, ultimately, is the reason the Python % was given its definition -- in the end, it has to do with operations in the ring of integers modulo n.
This article about modular arithmetic (in particular, the part about integers modulo n) could be a good starting point if you'd like to know more about this topic.

Related

Why does std::bit_width return 0 for the value 0, shouldn't it return 1?

std::bit_width finds minimum bits required to represent an integral number x as 1+floor(log(x))
Why does std::bit_width return 0 for the value 0? Shouldn't it return 1, Since the number of bits required to represent 0 is 1?
Also, I think the 1 in the formula is an offset.
There is a strange bit of history to bit_width.
The function that would eventually become known as bit_width started life as log2, as part of a proposal adding integer power-of-two functions. log2 was specified to produce UB when passed 0.
Because that's how logarithms work.
But then, things changed. The function later became log2p1, and for reasons that are not specified was given a wider contract ("wide contract" in C++ parlance means that more stuff is considered valid input). Specifically, 0 is valid input, and yields the value of 0.
Which is not how logarithms work, but whatever.
As C++20 neared standardization, a name conflict was discovered (PDF). The name log2p1 happens to correspond to the name of an IEEE-754 algorithm, but it's a radically different one. Also, functions in other languages with similar inputs and results use a name like bit_length. So it was renamed to bit_width.
And since it's not pretending to do a logarithm anymore, the behavior at 0 can be whatever we want.
Indeed, the Python function int.bit_length has the exact same behavior. Leading zeros are not considered part of the bit length, and since a value of 0 contains all leading zeros...
Because mathematically it makes sense:
bit_width(x) = log2(round_up_to_nearest_integer_power_of_2(x + 1))
bit_width(0) = log2(round_up_to_nearest_integer_power_of_2(0 + 1))
= log2(1)
= 0
To elaborate what was said in the comments:
Assume "bit width" means "least number of bits required to store the (nonnegative integer) number". Intuitively we need at least log2(n) bits rounding up, so it is a formula close to ceil(log2(n)), so 255 would require ceil(log2(255)) = ceil(7.99..) = 8 bits, but this doesn't work for powers of 2, so we can add a fudge factor of 1 to n to get ceil(log2(n+1)). This happens to be mathematically equivalent to 1+floor(log2(n)) for positive n, but log2(0) is not defined or defined as something unuseful like negative infinitiy in the floor version.
If we use the ceiling formula for 0, we get the result. You can also see I didn't write out leading zeros, and as Nicol Bolas points out, 0 is all leading zeros.
n
bin(n)
bit_width(n)
8
1000
4
7
111
3
6
110
3
5
101
3
4
100
3
3
11
2
2
10
2
1
1
1
0
0

Why does ~n give -(n+1)?

I wanted to test what happens when I write this code. I can not explain the following case:
Input: 5
Output: -6
#include <iostream>
int lastBit(int n){ return ~(n); }
int main() { std::cout << lastBit(5); }
Computers express negative numbers in quite a specific way. Values are always stored as series of bits and there is no way of introducing negative sign, so this has to be solved differently: one of bits plays role of a negative sign.
But this is not all - the system must be designed to handle maths properly (and ideally, the same way as for positive numbers).
So for instance 0 == 0b00000000. If you subtract 1 from 0, you get -1, but from the binary perspective, due to "binary underflow", 0b00000000 - 0b00000001 == 0b11111111, hence 0b11111111 == -1.
If you then subtract 1 from -1, you get 0b11111111 - 0b00000001 == 0b11111110 == -2. But 2 == 0b00000010, which shows, why -2 != ~2 (and the same rule applies to next values).
The very short, but maybe more intuitive answer might be: "-5 != ~5, because there is only one zero binarily (eg. 0 == -0), so there is always one more negative value than positive ones"
Not on all systems but on systems that use complement of two for signed values. By definition there, the binary representation of negative X = -n, where n is a positive integer, is ~n + 1, which allows signed and unsigned addition operations to be same.
Until C++20 result of ~(n) for signed negative n here would be undefined, because it depends on platform and compiler. In C++20 it's required to behave as if complement of two is used.
I found out the following
5 = 0101
Therefore, ~(5) = 1010
The 1 at the most significant bit denotes negativee (-)
010 = 6
Therefore, output is -6
Since this is a 2's complement machine

Simple Modulo Operations

So I am learning C++, and in one of the books I'm reading, there is an example for finding GCF (greatest common factor). The function is as follows:
int gcf(int a, int b) {
if(b == 0) {
return a;
}
else {
return gcf(b, a%b);
}
}
What I don't understand is that if I put in 15 and 5 for example, then
a = 15
b = 5
b is not 0 so then the else statement executes
(5, 15%5 = 0) so since b is now 0 it returns, a, which is 5.
That makes sense, but if I reverse the numbers, why/how do I get the same answer?
a = 5
b = 15
b is not 0 so then the else statement executes
(15, 5%15) but 5%15 is .3 or 1/3, but in C++, 5%15 returns 5.
I don't understand where 5 comes from, if anything, since it's an integer, I thought it maybe return 0 but it doesn't return 15, so it can't be.
What you're doing is integer calculation - no floating points or fractions involved.
5 % 15 is actually the remainder you get after dividing 5 by 15, and that is, of course, 5 (the quotient would be 0).
15 | 5 | 0 <-- this is the first call gcf(5, 15)
0
---
5 | 15 | 3 <-- this is the first recursive call gcf(15, 5)
15
---
0 | 5 | <-- this is the second recursive call gcf(5, 0), returns 5
Modulo operator is different from division,usually when we divide the return value is a quotient but when you use modulo operator return value is its reminder.
so in your case when
**
a=5 and b = 15, a%b the return value of this was 0 ,
**
that is the reason why it returned 5. check the following links for greater clarity on modulo operator
http://www.cplusplus.com/doc/tutorial/operators/
http://www.cprogramming.com/tutorial/modulus.html
In integer division, 5/15 = 0. Since 5%15 is the remainder, it needs to be 5. C and C++ mandate that for any a and b, a/b*b + a%b = a.
If you are interested, the piece of code you have written there is called Euclid's Algorithm which is based upon Euclid's Lemma (big surprise there). Although I heard from a professor that some people might refer to different formulations of Euclid's Lemma. My Higher Algebra book particularly refers to it as "Equal gcd's".
It states:
Let a, b, q, and c be integers with a=qb+c. Then gcd(a,b)=gcd(b,c)
gcd(a,b) refers to the greatest common divisor of a and b.
This seems to be precisely what you are doing in your program.
Any integer a can be written as the qb+c for any b. This means that a is a product qb plus some remainder c. The remainder here is what you are calculating when you use the % operator. If we let a = 12 and b = 5 then can write 12=5q+c. Let q be 2. Then our remainder c is 2. Perhaps these things are elementary but hopefully this is nice background to supplement your book's explanation.

rand() function in c++

i am not quite sure how this function in c++ works:
int rand_0toN1(int n) {
return rand() % n;
}
Another tutorial on internet says to get a random number between a range you need to do something different however, with a being first number in range and n is number of terms in range:
int number = a + rand( ) % n;
I have read that it is supposed to return a random number between the value of 0 and n-1, but how does it do that? I understand that % means divide and give the remainder (so 5 % 2 would be 1) but how does that end up giving a number between 0 and n-1? Thanks for help in understanding this. I guess i don't understand what the rand() function returns.
The modulo (remainder) of division by n > 0 is always in the range [0, n); that's a basic property of modular arithmetic.
a + rand() % n does not return a number in the range [0, n) unless a=0; it returns an int in the range [a, n + a).
Note that this trick does not in general return uniformly distributed integers.
rand returns a pseudorandom value bewtween 0 and RAND_MAX, which is usually 32767.
The modulo operator is useful for "wrapping around" values:
0 % 5 == 0
1 % 5 == 1
2 % 5 == 2
3 % 5 == 3
4 % 5 == 4
5 % 5 == 0 // oh dear!
6 % 1 == 1
// etc...
As such, by combining that pseudorandom value with a modulo, you're getting a pseudorandom value that's guaranteed to be between 0 and n - 1 inclusive.
According to your own example, you seems to understand how it works.
rand() just returns an integer pseudorandom number between 0 and RAND_MAX, then you apply the modulo operator to that number. Since the modulo operator returns the remainder of division of one number by another, a number divided by N will always return a number lesser than N.
The rand() function returns an integral value in the interval
[0...RAND_MAX]. And the results of x % n will always be in the
range [0...n) (provided x >= 0, at least); this is basic math.
Please take a look here :
http://www.cplusplus.com/reference/clibrary/cstdlib/srand/
Usually you "seed" it with the time function. And then use the modulus operator to specify a range.
The c++ rand() function gives you a number from 0 to RAND_MAX (a constant defined in <cstdlib>), which is at least 32767. (from the c++ documentation)
The modulus (%) operator gives the remainder after dividing. When you use it with rand() you are using it to set an upper limit (n) on what the random number can be.
For example, lets say you wanted a number between 0 and 4. Calling rand() will give you an answer between 0 and 32767. rand() % 5, however, will force the remainder to be 0, 1, 2, 3, or 4 depending on the value rand() returned (if rand() returned 10, 10%5 = 0; if it returned 11, 11%5 = 0, etc.).

Need help with C++ Loops Exercise

From Cay Horstmann's "C++ For Everyone"
Chapter 4: Loops
Write a program that adds up the sum of all odd digits of n. (For example, if n is 32677, the sum would be 3 + 7 + 7 = 17)
I don't know how to make the computer "see" the numbers like separate them
n % 10 gets the value of the one's digit. You can figure it out from there right?
Here's a hint. C++ has the modulus operator %. It will produce the remainder when two numbers are divided together. So if I wanted to know the last digit in a number which was greater than 10 I would modulus 10 and get the result
int lastDigit = number % 10;
The last digit of a base-10 integer i is equal to i % 10. (For reference, % is the modulus operator; it basically returns the remainder from dividing the left number by the right.)
So, now you have the last digit. Once you do, add it to a running total you're keeping, divide i by 10 (effectively shifting the digits down by one place), or in your case 100 (two places), and start back at the beginning. Repeat until i == 0.
People here rather not provide you with the answer to your exercise, but to provide you with hints so that you can find the answer on your own and more importantly understand it.
To start, the following arithmetic operations will help you:
loop:
right_most_digit = n % 10
n = n / 10
end_loop