Saturn
Saturn

Reputation: 18139

Arithmetic gives unexpected value in ruby

Why is this:

((256-438)^2)+((227-298)^2)

Giving me -253 when it should be 38165 instead?

Upvotes: 4

Views: 193

Answers (6)

typo
typo

Reputation: 1071

Use ** not ^

Code should be - ((256-438)**2)+((227-298)**2)

** is the Exponentiation or 'power of' operator.

The Exponentiation operator

Raises number to the power of second number, which may be negative or fractional.

2 ** 3 #=> 8

2 ** -1 #=> (1/2)

2 ** 0.5 #=> 1.4142135623731

^ is the bitwise XOR operator.

The XOR operator

The XOR operator implements an exclusive OR which means that it will set the bit to 1 in the output if only one of the corresponding bits in the inputs are set to 1:

(a = 18).to_s(2) #=> "10010"

(b = 20).to_s(2) #=> "10100"

(a ^ b).to_s(2) #=> "110" (leading zeros are omitted)

Upvotes: 0

Andrew Cooper
Andrew Cooper

Reputation: 32576

^ is the XOR operator, not exponeniation.

Upvotes: 2

Maxpm
Maxpm

Reputation: 25551

^ is the bitwise XOR operator, according to http://phrogz.net/programmingruby/language.html. Not the "power of" operator.

Upvotes: 2

Paul Creasey
Paul Creasey

Reputation: 28824

^ is the bitwise exclusive OR operator (XOR)

** is the exponent operator, use:

((256-438)**2)+((227-298)**2)

Upvotes: 15

Terry Wilcox
Terry Wilcox

Reputation: 9040

Try ((256-438)**2)+((227-298)**2)

Upvotes: 2

Mu Mind
Mu Mind

Reputation: 11194

Because ^ is the operator for XOR, not exponents. Try ** instead.

Upvotes: 6

Related Questions