What is used in ruby?

Possible duplicate:
Using a caret (^) character in Ruby

So, I was playing with some code, and I tried to play with the power operator. So I thought that maybe I could use a carriage ( ^ ) for this purpose, but after using it in:

 for i in 0..10 puts "#{i} #{1^i}\n" end 

I have really funny results

 0 - 1 1 - 0 2 - 3 3 - 2 4 - 5 5 - 4 6 - 7 7 - 6 8 - 9 9 - 8 10 - 11 

The only pattern I see is -1 on an odd number and +1 on an even number, but then when I try:

 for i in 0..10 puts "#{i} #{2^i}\n" end 

I get:

 0 - 2 1 - 3 2 - 0 3 - 1 4 - 6 5 - 7 6 - 4 7 - 5 8 - 10 9 - 11 10 - 8 

wow! So, I continued to climb to 4^i and drew them, 1^i & 3^i came out with decent patterns , but 2^i & 4^i were just above the place where there were no visible patterns (albeit unlikely) only with 11 points, so I came to you, ladies and gentlemen, who asked you:

What on earth ^ used for ?!

+6
source share
1 answer

In most programming languages, ^ is the XOR operator ( Exclusive or on Wikipedia ). XOR is one of the most important operations in the CPU, it is often used for zero registers (I think a ^= a ), because it is fast and has a short operation code.

For the power function you should use, for example. ** (e.g. in ruby), java.lang.Math.pow , math.pow , pow , etc.

In fact, I could not name a programming language that uses ^ . It is used in LaTeX for formatting (as a superscript rather than a power function, technically). But there are two options that I see all the time: ** (since the power function is directly related to multiplication) and pow(base, exp) .

Note that you can calculate integer powers of 2 faster with shifts.

+18
source

Source: https://habr.com/ru/post/920387/


All Articles