Sandwich Conditions in Objective-C - objective-c

I'm trying the following condition, the compiler give no warning but the code does not seems to work. Should This work?
if (self.finishLine > hero.position.y > self.startHeight)
{
hero.position = CGPointMake( hero.position.x + translation.x, hero.position.y);
}

Comparison operators return boolean values.
(self.finishLine > hero.position.y > self.startHeight)
-> ((self.finishLine > hero.position.y) > self.startHeight)
-> ((<0 or 1> > self.startHeight)
I doubt that self.startHeight is ever less than 1, let alone less than 0.
The correct form in C is:
((self.finishLine > hero.position.y) && (hero.position.y > self.startHeight))

I have not tried it but I believe it is a valid expression. AFAIK Objective C does not support sandwiches..
(a > b > c) should evaluate to TRUE or FALSE respectively YES or NO. But how? The compiler would start from left to right here as all operators are equal. (a > b) will evaluate to YES or NO. Those are internally represented by 1 and 0. 1 and 0 may be larger than c or not.
I wonder if the compiler throws a warning at least.
Did you go for it and tried it?

Related

operators precedence and associativity in C

i would be grateful if somebody could help me with this problem. The book I am currently reading has a question
Q What will be the output?
#include <stdio.h>
void main()
{
int a = 3, b = 2;
a = a ==b==0;
printf("%d, %d",a,b);
}
The answer is given as
1,2 ( even on codeblocks got the same answers)
Now i understand that equality operator has precedence over the assignment operator.
So it must be a== b or b == 0 first
Then as both the above have the same operator, The associativity rule causes
a == b to be evaluated first.
But from here on I am lost!
How does one get to 1 and 2 as the answer?
See https://en.cppreference.com/w/cpp/language/operator_precedence
Note the line that says, "Operators that have the same precedence are bound to their arguments in the direction of their associativity." You can see the associativity for each operator on the far right column.
Note that equality operator is on line 10, with associativity left-to-right.
Note that assignment is line 16, so it has lower precedence than equality.
// original
a = a == b == 0
// precedence rule
a = (a == b == 0)
// associativity rule
a = ((a == b) == 0)
I believe that the equality operator does does not have precedence over the assignment operator. C just works itself from left to right.
in
a = a == b == 0;
a is assigned to everything on the right of the equal sign.
On the right side of the equal sign, a == b is evaluated to false. Then we compare equality of the answer to a==b with 0. In c, 0 is equal to false, so we get true. This is our answer to "everything to the right of the equal sign". So then, we assign that value(true) to a, which is an integer. Because of automatic conversion, true is converted to 1 and assigned to a. Now a equals 1.
As an equation, the above process can be represented as: a = (( a == b ) == 0)
Hope this makes sense. Tell me if I need to clarify further.

Does `if` work only in combination with `else` in Series.apply(lambda x)?

I'm getting a SyntaxError for:
housing['Lot Area'].apply(lambda x: x + 50000 if x > 20000)
When I add else, the code runs fine:
housing['Lot Area'].apply(lambda x: x + 50000 if x > 20000 else x)
Does if only work in combination with else here? I'd like to increment x with 50000 only if x > 20000 -- otherwise I'd like x to remain unchanged. I find the else part a bit redundant here. Besides the first question before, is there any way to write this code without the else part?
Base on your description , even apply is not need here
housing.loc[housing['Lot Area']>20000,'Lot Area']+=50000
Comment from Alex :
if the if statement resolves to False for a value, then apply() doesn't return and just lets the value in the Series as it is
you're getting a SyntaxError because you are typing invalid syntax. the ternary operator must be used like
expression if bool else other_expression

What is the difference between == and <= in this case

I was working on making a game, and I was wondering why the construct with the == operator doesn't work while the lower one does. I used an NSLog message afterwards to test.
if (pipe.position.x == bird.position.x){ no idea why this doesn't work
if ((pipe.position.x <= bird.position.x) & (pipe.position.x > bird.position.x - 1)){
This is because one (or both) of the position.x's are a floating-point2 value with a non-zero difference1 between the two position values such that only the second condition is true.
Since p <= b is true for all values that make p == b true, to see why this works "unexpectedly" let's choose some values such that the expression p == b is false2 yet p < b is true and p > b - 1 is true.
Given p = 3.2 (pipe) and b = 3.7 (bird), as an example, then
p == b
-> 3.2 == 3.7
-> false
but
(p <= b) & (p > b - 1)
-> (3.2 <= 3.7) & (3.2 > 3.7 - 1)
-> (3.2 <= 3.7) & (3.2 > 2.7)
-> true & true
-> true
Instead, to detect when the bird "is crossing" the pipe, assuming that x increases to the right, consider
// The bird's head to the "right" of the pipe leading edge..
bird_x >= pipe_x
// ..but bird's butt is not to the "right" of the pipe trailing edge.
// (Also note use of the &&, the logical-AND operator)
&& (bird_x - bird_width <= pipe_x + pipe_width)
Of course, using a non-rectangle (or forgiving overlap) collision detection would lead to less frustrating flapping!
1 This issue occurs because there are some particular floating-point values (but there are no integer values) which can cause the observed effect.
First, reiterate the assumption that p is not equal to b, given that the first condition does not succeed. Let's suppose then that p <= b is written as p == b || p < b but since p == b is false , we can write it as p < b by tautology.
Since both clauses in the second condition are true (such that true && true -> true), we have the rules: 1) p < b is true, and 2) p > b - 1 is true.
Rewriting p < b as p - b < 0 and p > b - 1 as p - b > -1, and then replacing p - b with x yields: x < 0 and x > -1. However, there is no integer value of x which satisfies -1 < x < 0.
(In first section, where p = 3.2 and b = 3.7, x = (p - b) = 0.5 which satisfies the given constraints when x is not restricted to an integer value.)
2 With all above aside, it is possible for p and b to be "very close but different" floating-point values such that there is a non-zero difference between them - due to rounding, they may even be displayed as the same integer value! See How dangerous is it to compare floating point values? and related questions for the cause and "odd" behavior of such when using ==.
If this is the case then round to integer values and use an integer comparison, or; rely entirely on relational comparison such as shown in the proposed condition, or; use epsilon comparison for "nearly equal" of floating-point values.
if you choose abs(pipe.position.x) == abs(bird.position.x) the first condition may satisfy.

Conditional statement in Objective C with two comparison operators in a single clause

I've been learning Objective C lately, and I came across some code for using the accelerometer in an iPhone app. It works perfectly; however, there's one if-statement in the code which I simply cannot understand (both the meaning and why it works). The specific chunk is this:
if (0.2f < deviceTilt.y > -0.2f){position.x = 0;}
I just can't figure out the condition, and I hadn't seen the use of two comparison operators in one single clause before.
Hope somebody can help me out!
PS: The whole project can be found in this link: http://www.ifans.com/forums/showthread.php?t=151394
This is evaluated like:
let y := .1
if ((.2 < y) > -.2)
if (false > -.2)
false is treated as an int
if (0 > -.2)
if (true)
let y := .3
if ((.2 < y) > -.2)
if (true > -.2)
true is treated as an int
if (1 > -.2)
if (true)
-> always true
most likely this was meant:
if ((.2 < y) && (y > -.2))
This is certainly atypical and most people wouldn't like it. To really understand what is going on, you have to understand C's operator precedence. See: http://www.swansontec.com/sopc.html.
Let's analyze the statement knowing that conditionals associate left-to-right:
1) 0.2f < deviceTilt.y. This is either true (which is 1) or false (which is 0)
2) The result of (1) > -0.2f. Which should always be true.
So this is the same as if(1) or always true

Weird Objective-C Mod Behavior for Negative Numbers

So I thought that negative numbers, when mod'ed should be put into positive space... I cant get this to happen in objective-c
I expect this:
-1 % 3 = 2
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
But get this
-1 % 3 = -1
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
Why is this and is there a workaround?
result = n % 3;
if( result < 0 ) result += 3;
Don't perform extra mod operations as suggested in the other answers. They are very expensive and unnecessary.
In C and Objective-C, the division and modulus operators perform truncation towards zero. a / b is floor(a / b) if a / b > 0, otherwise it is ceiling(a / b) if a / b < 0. It is always the case that a == (a / b) * b + (a % b), unless of course b is 0. As a consequence, positive % positive == positive, positive % negative == positive, negative % positive == negative, and negative % negative == negative (you can work out the logic for all 4 cases, although it's a little tricky).
If n has a limited range, then you can get the result you want simply by adding a known constant multiple of 3 that is greater that the absolute value of the minimum.
For example, if n is limited to -1000..2000, then you can use the expression:
result = (n+1002) % 3;
Make sure the maximum plus your constant will not overflow when summed.
We have a problem of language:
math-er-says: i take this number plus that number mod other-number
code-er-hears: I add two numbers and then devide the result by other-number
code-er-says: what about negative numbers?
math-er-says: WHAT? fields mod other-number don't have a concept of negative numbers?
code-er-says: field what? ...
the math person in this conversations is talking about doing math in a circular number line. If you subtract off the bottom you wrap around to the top.
the code person is talking about an operator that calculates remainder.
In this case you want the mathematician's mod operator and have the remainder function at your disposal. you can convert the remainder operator into the mathematician's mod operator by checking to see if you fell of the bottom each time you do subtraction.
If this will be the behavior, and you know that it will be, then for m % n = r, just use r = n + r. If you're unsure of what will happen here, use then r = r % n.
Edit: To sum up, use r = ( n + ( m % n ) ) % n
I would have expected a positive number, as well, but I found this, from ISO/IEC 14882:2003 : Programming languages -- C++, 5.6.4 (found in the Wikipedia article on the modulus operation):
The binary % operator yields the remainder from the division of the first expression by the second. .... If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined
JavaScript does this, too. I've been caught by it a couple times. Think of it as a reflection around zero rather than a continuation.
Why: because that is the way the mod operator is specified in the C-standard (Remember that Objective-C is an extension of C). It confuses most people I know (like me) because it is surprising and you have to remember it.
As to a workaround: I would use uncleo's.
UncleO's answer is probably more robust, but if you want to do it on a single line, and you're certain the negative value will not be more negative than a single iteration of the mod (for example if you're only ever subtracting at most the mod value at any time) you can simplify it to a single expression:
int result = (n + 3) % 3;
Since you're doing the mod anyway, adding 3 to the initial value has no effect unless n is negative (but not less than -3) in which case it causes result to be the expected positive modulus.
There are two choices for the remainder, and the sign depends on the language. ANSI C chooses the sign of the dividend. I would suspect this is why you see Objective-C doing so also. See the wikipedia entry as well.
Not only java script, almost all the languages shows the wrong answer'
what coneybeare said is correct, when we have mode'd we have to get remainder
Remainder is nothing but which remains after division and it should be a positive integer....
If you check the number line you can understand that
I also face the same issue in VB and and it made me to forcefully add extra check like
if the result is a negative we have to add the divisor to the result
Instead of a%b
Use: a-b*floor((float)a/(float)b)
You're expecting remainder and are using modulo. In math they are the same thing, in C they are different. GNU-C has Rem() and Mod(), objective-c only has mod() so you will have to use the code above to simulate rem function (which is the same as mod in the math world, but not in the programming world [for most languages at least])
Also note you could define an easy to use macro for this.
#define rem(a,b) ((int)(a-b*floor((float)a/(float)b)))
Then you could just use rem(-1,3) in your code and it should work fine.