Bionix1441
Bionix1441

Reputation: 2319

What does '<< ' mean ? And what this code mean?

I don't understand what is this doCalculatePi means or does, in the following example:

  public static double doCalculatePi(final int sliceNr) {
    final int from = sliceNr * 10;
    final int to = from + 10;
    final int c = (to << 1) + 1;
    double acc = 0;
    for (int a = 4 - ((from & 1) << 3), b = (from << 1) + 1; b < c; a = -a, b += 2) {
        acc += ((double) a) / b;
    }
    return acc;
}

public static void main(String args[]){
    System.out.println(doCalculatePi(1));
    System.out.println(doCalculatePi(2));
    System.out.println(doCalculatePi(3));
    System.out.println(doCalculatePi(4));
    System.out.println(doCalculatePi(10));
    System.out.println(doCalculatePi(100));
    }

I have printed the values to understand what the results are but I still have no clue what this code calculates. The conditions inside the loop are not clear.

Upvotes: 1

Views: 268

Answers (3)

mazhar islam
mazhar islam

Reputation: 5619

<< means left shift operation, which shifts the left-hand operand left by the number of bits specified by the right-hand operand (See oracle docs).

Say, you have a decimal value, 5 which binary representation is 101

Now for simplicity, consider,

byte a = (byte)0x05; 

Hence, the bit representation of a will be,

a = 00000101 // 1 byte is 8 bit

Now if you left shift a by 2, then a will be

a << 2
a = 00010100 //shifted place filled with zero/s

So, you may now understand that, left shift a by 3 means

a << 3
a = 00101000

For better understanding you need to study Bitwise operation.

Note, you are using int instead of byte, and by default, the int data type is a 32-bit signed integer (reference here), so you have to consider,

int a = 5;

in binary

a << 3
a = 00000000 00000000 00000000 00101000 // total 32 bit

Upvotes: 10

NaN
NaN

Reputation: 8601

My guess is that it approximates PI with

PI = doCalculatePi(0)+doCalculatePi(1)+doCalculatePi(2)+...

Just a guess.

Trying this

double d = 0;
for(int k = 0; k<1000; k++) {
    System.out.println(d += doCalculatePi(k));
}

gives me

3.0418396189294032
3.09162380666784
3.1082685666989476
[...]
3.1414924531892394
3.14149255348994
3.1414926535900394

Upvotes: 4

Matt
Matt

Reputation: 11805

<< is the Bitshift operator.

Basically, every number is represented as a series of binary digits (0's and 1's), and you're shifting each of those digits to the left by however many places you indicate. So for example, 15 is 00001111 and 15 << 1 is 00011110 (or 30), while 15 << 2 is (00111100) which is 60.

There's some special handling that comes into play when you get to the sign bit, but you should get the point.

Upvotes: 1

Related Questions