boskee / Minecraft

Simple Minecraft-inspired program using Python and Pyglet
MIT License
207 stars 33 forks source link

Improved performance by adding function which calcuates sine from cosine, but I'm not sure if it works good in every circumstances #41

Closed ghost closed 11 years ago

ghost commented 11 years ago

I improved performance (this commit: https://github.com/avelanarius/Minecraft/commit/2dbee32c6c182d7e4a475378f88fb319b60a6dab) by adding function which calcuates sine from cosine, but I'm not sure if it works good in every circumstances.

It uses following trigonometric identity: sin^2 x + cos^2 x = 1 with condition for negative sine. It should work faster, because sqrt is faster than sin. If you can, please check if it doesn't return inaccurate value in some circumstances. When I'll be sure that my implementation is correct, I'll merge it to boskee / Minecraft.

BertrandBordage commented 11 years ago

Sorry, but sin_from_cos is ~ 8 times slower than regular sin… Using iPython:

def sin_from_cos(degrees, cos_value):
    if degrees < 0.0:
        degrees += 2 * pi
    return sqrt(1.0 - cos_value * cos_value) * (1.0 if fmod(abs(degrees), 2 * pi) < pi else -1.0)

from math import cos, sin
c = cos(-3428.1)

%timeit sin_from_cos(-3428.1, c)
1000000 loops, best of 3: 772 ns per loop

%timeit sin(-3428.1)
10000000 loops, best of 3: 88.2 ns per loop
ghost commented 11 years ago

Sorry... tried to optimize too much...

BertrandBordage commented 11 years ago

No problem, I also looove optimizations :)