cburton
cburton

Reputation: 97

Why does 2- - - -1=3?

I recently ran into a bug using python (v3.6.8) and pandas (v0.23.4) where I was trying to subtract a date offset. However, I accidentally typed two -- signs and it ended up adding the date offset instead. I did some more experimenting and found that 2--1 will return 3. This makes sense since you could interpret that as 2-(-1), but you can go even farther and string a bunch of negatives together 2----1 will return 3. I also replicated this in R and it does the same thing. Can anyone help me understand what's happening here?

Upvotes: 1

Views: 167

Answers (4)

Eric Hilton
Eric Hilton

Reputation: 61

mathematically, it's correct. by why would a programming language allow that? maybe i just lack imagination, but i can't think of any reason why you would want to explicitly string together plus or minus signs. and if you did do that, it is likely a typo as in the original post. if it's done through variables, then it should definitely be allowed (ie, a = -1; 2 -a should be 3). some languages allow for i++ to increment i. and python allows i += 1 to increment i. not throwing a syntax error just seems confusing to me, even if it is mathematically correct.

Upvotes: 2

Skipper
Skipper

Reputation: 396

2 - - - - 1 is the same as 2 - ( - ( - ( - 1))) what is the same as

2 - ( - (1)) = 2 + 1 = 3

As soon as number of minuses is even you actually do "+".

Upvotes: 5

Jacob Gasser
Jacob Gasser

Reputation: 51

As some math teachers say, "boom ching!"

What you are actually doing is adding 2 + 1.

In math, when you have two subtraction symbols next to each other, they combine to form an addition symbol. At least that is what they taught me in school.

So really, it is more like this,

2 + + 1

Which everyone knows 2 + 1 = 3

(and welcome to Stack Overflow!)

Upvotes: 0

Joseph Potter
Joseph Potter

Reputation: 156

Since it is being negated every time, an even number of - signs will be equivalent to a single + sign, and an odd number is equivalent to a - sign. so

2---1

Will evaluate to 1 and

2----1

will evaluate to 3

Upvotes: 3

Related Questions