Reputation: 10341
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]
Upvotes: 3
Views: 2782
Reputation: 61498
The problem is the & 7fffffff bit in return statement. First, I'm not sure what that operation is. Maybe a bit-shift?
A bit mask. <<
is used for shifting. &
is bitwise-AND. 7fffffff
, interpreted as a hexadecimal number, is a quantity that, if re-written in binary, has 31 bits, all of which are 1. The effect is to select the low-order 31 bits of the value.
To tell Python that 7fffffff
should be interpreted as a hexadecimal number, you must prefix it with 0x
, hence 0x7fffffff
.
Second, I'm not sure how to do that operation in Python.
The same way as in the pseudocode (i.e. with &
).
Upvotes: 1
Reputation: 10489
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
Upvotes: 3
Reputation: 20229
I replaced 7FFFFFFF
with 0x7FFFFFFF
in your existing code and tried plugging in some random values and all the answers which I got were in [-1, 1].
Upvotes: 1