Clean obfuscated code

One way to obfuscate code is clever use of arcane programming language syntax. Hackers are able to write completely unrecognizable code by exploiting dark corners of programming techniques and languages. Some of these attempts are quite impressive.

But it’s also possible to write clean source code that is nevertheless obfuscated. For example, it’s not at all obvious what the following Python code computes.

def f(x):
    return 4*x*(1-x)

def g(x):
    return x**3.5 * (1-x)**2.5

sum = 0
x = 1/7.0
N = 1000000

for _ in range(N):
    x = f(x)
    sum += g(x)

print(sum/N)

The key to unraveling this mystery is a post I wrote a few days ago that shows the x‘s in this code cover the unit interval like random samples from a beta(0.5, 0.5) distribution. That means the code is finding the expected value of g(X) where X has a beta(0.5, 0.5) distribution. The following computes this expected value.

 \int_0^1 g(x) \, dF_X &=& \frac{1}{\pi} \int_0^1 x^{3.5} (1-x)^{2.5} x^{-0.5} (1-x)^{-0.5} \, dx \\ &=& \frac{1}{\pi} \int_0^1 x^3 (1-x)^2\, dx \\ &=& \frac{1}{\pi} \frac{\Gamma(4) \Gamma(3)}{\pi \Gamma(7)} \\ &=&\frac{1}{60\pi}

The output of the program matches 1/60π to six decimal places.

Related post: What does this code do?

Comments are closed.