List Info

Thread: the sign of a number is omitted when squaring it. -2**2 vs (-2)**2




the sign of a number is omitted when squaring it. -2**2 vs (-2)**2
user name
2006-11-04 19:23:30
Jacob Fugal wrote:
> On 11/3/06, noreplyrubyforge.org
<noreplyrubyforge.org> wrote:
>> Due to the way ruby interprets formula's, squaring
a negative number
>> isn't possible unless you use brackets. This caught
me unaware, and
>> might be counterintuitive for more people.
>>
>> irb(main):018:0> -2**2
>> => -4
>> irb(main):019:0> (-2)**2
>> => 4
> 
> The "problem" lies in the confluence of
precedence with the syntax of
> literals. It should be obvious that exponentiation (**)
binds with a
> higher precedence than unary negation /as an
operation/, because
> exponentiation has precedence of multiplication (and
unary negation is
> essentially multiplication by -1). The confusion is
because there's a
> misconception the the "-" in "-2"
is part of the literal when it is
> not -- it is an operation applied to the object derived
from the
> literal "2".

Any yet

irb(main):002:0> -2.abs
=> 2

So there are cases where the operation of
"concatenating characters to 
form a literal" has higher priority than an operation
on objects.

It's not simply a matter of `-' having priority over `.', as
can be seen 
from this example:

irb(main):006:0> x=2
=> 2
irb(main):007:0> -x.abs
=> -2

So "dot" does have priority over "unary
minus", but not over literal 
formation.

Why shouldn't literals always take precedence? Does it beak
too many 
habits from ancestor languages (perl, as pointed out)? Is it
too hard to 
parse?

-- 
       vjoel : Joel VanderWerf : path berkeley edu : 510 665
3407

the sign of a number is omitted when squaring it. -2**2 vs (-2)**2
user name
2006-11-05 17:30:27
Hi,

In message "Re: [ ruby-Bugs-6468 ] the sign of a number
is omitted when squaring it. -2**2 vs (-2)**2"
    on Sun, 5 Nov 2006 04:23:30 +0900, Joel VanderWerf
<vjoelpath.berkeley.edu> writes:

|Any yet
|
|irb(main):002:0> -2.abs
|=> 2
|
|So there are cases where the operation of
"concatenating characters to 
|form a literal" has higher priority than an operation
on objects.

People with mathematical background demands precedence for
** being
higher than that of unary minus.  That's the reason.

							matz.


[1-2]

about | contact  Other archives ( Real Estate discussion Medical topics )