Oh, apologies, I forgot to convert the `sign` to Int64. Changing the line
in question to
return (int(sign(x))*(rand() < abs(x)), int(sign(y))*(rand() < abs(y)))
speeds up things to 300 nanoseconds per call.
In any case, the original question still stands: could this be improved?
On Wednesday, December 3, 2014 9:48:11 AM UTC-5, DumpsterDoofus wrote:
>
> Hello everyone,
>
> I'm trying to make a function (let's call it `return_direction`) which
> takes in a Float between 0 and 2*pi, and randomly returns one of the
> following lattice vectors {(0,0), (1,0), (0,1), (1,1)}, weighted in such a
> way that the expectation value of `return_direction(theta)` is
> `(cos(theta), sin(theta))`.
>
> To do that, I implemented the following:
>
> function return_direction2(theta::Float64)
>
>
> x = cos(theta)
>
>
> y = sin(theta)
>
>
> return (sign(x)*(rand() < abs(x)), sign(y)*(rand() < abs(y)))
>
>
> end
>
>
> One can check that this indeed gives the proper expectation value. To test
> it's speed, I ran the following test:
>
> function test()
>
>
> (i1, i2, x, y, a) = (0,0,0,0,10^6)
>
>
> for i in 1:a
>
>
> (i1, i2) = return_direction(0.22)
>
>
> x += i1
>
>
> y += i2
>
>
> end
>
>
> println((x/a,y/a))
>
>
> end
>
>
> Running `@time test()` gives an execution time of 0.7 seconds on my
> computer, or roughly 700 nanoseconds per `return_direction` call.
> Ordinarily this would be fine, but `return_direction` is used in a
> lightweight script where it is called frequently, and it ends up taking a
> decent chunk of the runtime, so I was wondering if there was a way to speed
> this up.
>
> Presumably there isn't that much that can be sped up, other than the line
>
> return (sign(x)*(rand() < abs(x)), sign(y)*(rand() < abs(y)))
>
>
> Here it multiplies a Bool and an Int64, which might result in a
> type-conversion slowdown. Is this the case? If so, can I speed it up by
> modifying it? Alternately, is there a faster method of returning a random
> lattice vector that on average points in a particular direction `theta`?
>