Quantcast
Viewing latest article 25
Browse Latest Browse All 67

Answer by ceilingcat for Tips for golfing in C

Try cpow() instead of cos()

Instead of

double y=cos(M_PI*2*x);

try something like

double y=cpow(-1,x*2);

This uses Euler's formula, a little complex analysis and the observation that assigning a complex to a double yields the real part (careful with variadic function calls and other subtleties).

\$\cos 2\pi x+j\sin 2\pi x=e^{j2\pi x}=e^{j\pi 2x}=\left(-1\right)^{2x}\$

This type of trick can be used to reduce

double y=cpow(-1,x/2);

into

double y=cpow(1i,x);

because \$\left(-1\right)^\frac{x}{2}=j^\frac{2x}{2}=j^x\$

Edit: Equations now inline \$\LaTeX\$ instead of images.


Viewing latest article 25
Browse Latest Browse All 67

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>