Swirl Perlin Noise Generator

I have this code to generate 1D noise in obj-c, it works fine:

- (float)makeNoise1D:(int)x { x = (x >> 13) ^ x; x = (x * (x * x * (int)_seed + 19990303) + 1376312589) & RAND_MAX; return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & RAND_MAX) / 1073741824.0); } 

Now I'm trying to play it in Swift, but it always fails and shows EXEC_BAD_INSTRUCTION on return. Here is what it looks like now, I had to spit out the final expression, but I'm sure that is not a problem.

 func makeNoise1D(var x : Int) -> Float{ x = (x >> 13) ^ x; x = (x * (x * x * seed! + 19990303) + 1376312589) & 0x7fffffff var inner = (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff return ( 1.0 - ( Float(inner) ) / 1073741824.0) } 

I have already tried many different butts and divided into subexpressions, but still fails. The only thing I realized was that the first and last line worked. (Most of my test cases x were set to 20, and the seed to 10, just to make it simple).

Thanks for the help!

+5
source share
1 answer

The exception is caused by an "arithmetic overflow" that occurs if the result of one of your calculations cannot be represented as Int .

Unlike (Objective-) C, adding and multiplying integers in Swift does not β€œwrap” or β€œtruncate,” but it causes an error if the result does not fit into the data type.

But instead, you can use Swift "overflow operators" &* and &+ , which always truncate the result:

 func makeNoise1D(x : Int) -> Float{ var x = x x = (x >> 13) ^ x; x = (x &* (x &* x &* seed! &+ 19990303) &+ 1376312589) & 0x7fffffff let inner = (x &* (x &* x &* 15731 &+ 789221) &+ 1376312589) & 0x7fffffff return ( 1.0 - ( Float(inner) ) / 1073741824.0) } 
+8
source

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


All Articles