Evaluation with bitwise operation - c++

When checking whether n is a 2's exponential number, I wrote the following line:
if(n&(n-1)!=0)
to my surprise, when n is 6, this is evaluated to false. Then if I change it to
if((n&(n-1))!=0)
I get the correct result.
EDIT:
I get it that != is evaluated first, but I still don't see how the result is false in the case where n = 6.
5!=0 is true
then 6&true should still be true right?

In expression you originally used, (n-1) != 0 is executed first, then n & is applied to its result.
At the first sight it might not look logical, but == and != have higher precedence than & or |.
It's a common C/C++ behavior and it has been already addressed by its criticism:
Operators in C and C++: Criticism of bitwise and equality operators precedence
Conceptually, operators | and & are like + and *, so having them with low precedence is not very intuitive and leads to questions like the one you posted.
Hint: in contact with any programming language, it is good to develop a habit of checking operator precedence topic whenever in doubt. Actually, you will find quite soon that you actually memorized it in the meantime.

I would say the order of precedence is very important in here. From your second attempt the result is correct as this is called operator precedence (or "order of operations"). Precedence of common operators is generally defined so that "higher-level" operations are performed first (i.e., advanced operations "bind more tightly")/ For simple expressions, operations are typically ordered from highest to lowest in the order:
Parenthesization
Factorial
Exponentiation
Multiplication and division
Addition and subtraction
A common pitfall is that inner ( that cause to change the whole balance. Same concept, however bit-twise operations have the lowest priorities.

Related

C++ and PEMDAS Order of Precedence/Operations?

I have a question I was not able to find an answer for, I'm looking for some clarification.
From my understanding, C++ follows PEMDAS, is this correct?
So if I do something like 5/9 * (34/.2), it will have a hard time computing this formula due to the fact that the parentheses are at the end and not the front. Is this correct?
When I do (34/.2) *5/9, my formula works.
Any tips, pointers, guidance is appreciated. I feel like I'm really lost here.
The C++ Operator Precedence cppreference page contains the order of all operations in c++. It's a bit hard to digest all at once, but for simple mathematical operations you are concerned about row #5 and #6.
So yes, you can say that C++ somewhat follows PEMDAS, except, it doesn't have an exponent operator (see std::pow). But to clarify, multiplication and division are of the same priority (evaluated left to right) so are addition and subtraction (also left to right)
Assuming you mean in 5/9 * (34/.2) that 5/9 is a fraction, or in other words, the (34/.2) is not in the denominator, 5/9 * (34/.2) and (34/.2) * 5/9 should in theory evaluate to the same thing, right?
The reason they don't is because of integer division. When you write 5/9 what you should get is 0.555556, but because both 5 and 9 are integers, the / operator returns only the integral part of the result, in this case 0. However, when you evaluate the brackets first, you start by dividing an integer by a non-integer value (in this case, double). This returns a double result which when multiplied by 5 gives another double result, and dividing it by 9 doesn't do the integer division (because the first operand is double).
To reclarify the fault is not that the order is wrong, it's because of unexpected integer division. You can fix this problem by changing 5 into 5.0. This way, it's a double value and the / operator will never do integer division.
The simple answer is "Yes" C++ follows the standard order of precedence.
I would note that in PEMDAS the E stands for "exponent" and there is no way to express that in C++ you need to make a function call to achieve it but the rest is correct.
Definition:
P Parathasis first.
E Exponent second.
MD Multiplication and Division third (have the same precedence)
AS Addition and Subtraction fourth (have the same precedence)
MD happen left to right
AS happen left to right
5/9 * (34/.2)
it will have a hard time computing this formula due to the fact that the parentheses are at the end and not the front. Is this correct?
Wrong. The above expression is well define in maths and in C++ and has the same meaning.
(34/.2) *5/9
my formula works. Any tips, pointers, guidance is appreciated.
These are not the same expression. Multiplication and division have the same precedence and are applied left to right. You have changed the order of how these operators are applied. But you say they are supposed to be associative (i.e. order is not important). That is true. But you also have to throw in the type information. One easy thing to forget is that integer division is not what you expect (it throws away the remainder).
Version 1:
5/9 * (34/.2)
34/.2 => P1 170.0
5/9 => P2 0 // Integer division
P2 * P1 => P3 0
Version 2
(34/.2) *5/9
34/.2 => P1 170.0
P1 * 5 => P2 850.0
P2 / 9 => P3 94.4

Mathematically defined result of an expression

What does mathematically defined result mean?
There is a quote from 5/4:
If during the evaluation of an expression, the result is not
mathematically defined or not in the range of representable values for
its type, the behavior is undefined.
There's a note right after this statement, which provides some types of examples:
[ Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —end note ]
For example, 0/0 is not mathematically defined.
The case of 1/0 is slightly different, but in practice, for the C++ standard you can be sure that it's not viewed as mathematically defined.
The mathematical way to state this would be that the behavior is undefined iff the inputs are not elements of the natural domain of the function.
(The second part, about results being representable, translates to a restriction on the codomain of the function)
It depends on context. Mathematically not defined means simply: it is not defined under mathematics.
Suppose you want to divide by 0 but it is not defined : Division is the inverse of multiplication. If a \ b=c, then b * c=a.
But if b=0 , then any multiple of b is also 0 , and so if a != 0 , no such c exists.
On the other hand, if a and b are both zero, then every real number c satisfies b * c=a. Either way, it is impossible to assign a particular real number to the quotient when the divisor is zero. (From wikipedia).
In algebra, a function is said to be "undefined" at points not in its domain.
In geometry,In ancient times, geometers attempted to define every term. For example, Euclid defined a point as "that which has no part". In modern times, mathematicians recognized that attempting to define every word inevitably led to circular definitions, and in geometry left some words, "point" for example, as undefined.
So it depends on context.
In programming context, you can assume that it means divide by 0 or out of a defined range,causing overflow.
"Mathematically defined result" means the same thing it would mean in other similar contexts. Namely, there are constructs in most programming languages that represent, to that or another degree of accuracy, various mathematical concepts via some kind of natural mapping. This mapping is normally not defined in the documentation but is implied by reader's understanding of the natural language and common sense. In the C++ standard, it is referred in various places as "usual" or "ordinary" mathematical rules.
If you are unsure what this mapping is, I guess you can submit a defect report, but usually users of the standard know what 2+2 maps to, just as they know what words like if or the or appear or requirement mean.
It is true that 2+2 can be conceivably mapped to various mathematical constructs, not necessarily even connected to say Peano arithmetic, but that's not an "ordinary" or "usual" mathematics by the standards of C++ community.
So to answer the question, take an expression and map it to the corresponding mathematical concept. If it is not defined, then it is not defined.

Why isn't there a unary operator to get a multiplicative inverse? 0-x = -x ... 1/x =?

In C/C++ there is a unary minus operator, which returns the additive inverse of an arithmetic type (at least in most cases), i.e.
int x = 2, y = 2;
assert(x + (-x) == 0);
From a mathematical viewpoint it doesn't matter if one writes -x or 0-x, but from a programmer perspective it does. The sequence of instructions used to evaluate -x is in general different than the sequence of instructions used to evaluate 0-x! Having a unary minus operator in C++ does actually make sense despite being just syntactic sugar. So does a unary operator returning the multiplicative inverse, doesn't it? But why does C++ (like many (most?all?) languages) lack such an operator?
EDIT:
My main point is, that calculating an inverse of a number x (additive or multiplicative) does not require neutral elements (0 or 1 respectively) being processed by the computer. In fact 0 and 1 are non trivial entities for computers. While evaluating 0.0-x or 1.0/x is rather "simple" (precision is still a big problem here) for floating types (like float or double in C), it can become quite complex in general. Like for muti. precision floating point types 0.0-x is way more complex than -x and thus -x is not just handy but also generates more efficient code. On the other hand one has to introduce a function like inv(x) or x.inv() or whatever to achieve the same for multiplication (multiplicative inverse), instead of maybe just writing /x for 1.0/x ... Afaik the lack of such an operator is not only observable in C and C++ but in many other languages even in languages primarily designed for math which gets me puzzled ;)
Because there is no unary multiplicative inverse symbol in mathematics.
You either represent it as x^-1 or 1/x both of which can be down (albeit in a roundabout way for power) in C++ as well.
Unary negation only exists because it exists in mathematics.
Guvante's answer correctly points out that there's no common mathematical notation for the multiplicative inverse (though x-1 could loosely be thought of as a postfix operator).
In addition, C++ is derived from C, which is derived from B. The B language didn't even have floating-point arithmetic.
C itself is primarily a systems programming language, which a greater emphasis on integers than on floating-point arithmetic. A multiplicative inverse operation on integers is not particularly useful. (Well, it might be useful for modular arithmetic, but C unsigned types don't behave that way.)
The set of arithmetic operators hasn't changed much from B to C to C++. I think the addition of unary + was the biggest change.
Furthermore, there's really no great need for a multiplicative inverse operator even for floating-point. It's easy enough to write 1.0 / x -- and any decent compiler will generate the same code that as it would for a hypothetical inverse operator applied to x. (For some CPUs, that code would apply a division operator to the values 1.0 and x anyway.)

What is the name of this operator "^"?

I know that this operator does the "AND logical operator" but I don't know how to deal with it and if it deals with decimal numbers or just binary numbers ?
It is the the XOR operator:
XOR (Exclusive Or)
This operation is performed between two bits (a and b). The result is
1 if either one of the two bits is 1, but not in the case that both
are. There for, if neither or both of them are equal to 1 the result
is 0.
That is the bitwise XOR operator.
It performs an exclusive or operation.
It is not the logical AND, it's the bitwise XOR. It operates on integers, which are always binary numbers in C++, and may be overloaded for other types.
That's the bitwise XOR operator (so not logical, not AND) and decimal numbers are represented as binaries, so of course it works for them as well.
The logical AND is && and the bitwise AND is &.

What is >>> operation in C++

In this blog post the author has suggested the following as the bug fix:
int mid = (low + high) >>> 1;
Does anyone know what is this >>> operator? Certainly its not there on the following operator reference list:
http://msdn.microsoft.com/en-us/library/x04xhy0h%28v=vs.71%29.aspx
http://www.cplusplus.com/doc/tutorial/operators/
What is it and how does that solve the overflow problem?
>>> is not a part of C++. The blog contains code in Java.
Check out Java online tutorial here on Bitwise shift operators. It says
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
>>> is the logical right shift operator in Java.
It shifts in a zero on the left rather than preserving the sign bit. The author of the blog post even provides a C++ implementation:
mid = ((unsigned int)low + (unsigned int)high)) >> 1;
... if you right-shift unsigned numbers, preserving the sign bit doesn't make any sense (since there is no sign bit) so the compiler obviously uses logical shifts rather than arithmetic ones.
The above code exploits the MSB (32rd bit assuming 32 bit integers): adding low and high which are both nonnegative integers and fit thus into 31 bits never overflows the full 32 bits, but it extends to the MSB. By shifting it to the right, the 32 bit number is effectively divided by two and the 32rd bit is cleared again, so the result is positive.
The truth is that the >>> operator in Java is just a workaround for the fact that the language does not provide unsigned data types.
The >>> operator is in a Java code snippet, and it is the unsigned right shift operator. It differs from the >> operator in its treatment of signed values: the >> operator applies sign extension during the shift, while the >>> operator just inserts a zero in the bit positions "emptied" by the shift.
Sadly, in C++ there's no such thing as sign-preserving and unsigned right shift, we have only the >> operator, whose behavior on negative signed values is implementation-defined. To emulate a behavior like the one of >>> you have to perform some casts to unsigned int before applying the shift (as shown in the code snippet immediately following the one you posted).
The Java expression x >>> y is more or less equivalent to the C++ expression unsigned(x) >> y.
>>> is not C++ operator. I think it's an operator in Java language. I'm not sure though!
EDIT:
Yes. That is java operator. Check out the link to the article you provided. The article is using Java language!
It is a java operator, not related to C++.
However all the blog author does is change the division by 2 with a bit-wise right shift (i.e. right shifting the value by 1 is similar to dividing by 2 ^ 1).
Same functionality, different machine code output (bit shifting operations are almost always faster than multiplication/division on most architectures).