Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pseudo code to Python

Tags:

python

Just to be fully up front, this is regarding a homework, but this in itself is not the assignment. The assignment is using noise to create cool graphics. I have a bit of experience in Python but not enough to figure this simple thing out.

I'm having trouble generating a seeded-random [-1,1]. The pseudocode my teacher gave me is from Hugo Elias.

Pseudocode:

function Noise1(integer x, integer y)
    n = x + y * 57
    n = (n<<13) ^ n;
    return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);    
  end function

My attempt in Python:

def noise(x, y):
    n = x + y * 57
    n = (n<<5) ^ n;
    return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0)

The problem is the & 7fffffff bit in return statement. First, I'm not sure what that operation is. Maybe a bit-shift? Second, I'm not sure how to do that operation in Python. I had just removed that part, but I am getting huge negative numbers, nowhere near a [-1,1]

like image 592
jb. Avatar asked Mar 12 '26 10:03

jb.


1 Answers

The & symbol stands for bitwise AND
The ^ symbol stands for bitwise XOR

and the 7FFFFFFF is a HEX number.
In programming you can represent a hex number using 0x where 7FFFFFFF is 0x7FFFFFFF
Some further reading on hex numbers.

To do a binary AND in python you just use & 0x7FFFFFFF
see more here about bitwise operations in python

like image 59
Serdalis Avatar answered Mar 14 '26 00:03

Serdalis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!