0

I was reading Mathematics today and I saw this question. Please take a look at the question and Brevan Ellefsen's answer.

The question asks about taking the derivative of f(x)=x^(2*x^(3*x^(4*x^(5*x^(6*x^(7*x^(...))))))) (looks like SO doesn't support LaTeX)

Brevan Ellefsen didn't really answer the question, but took a numerical approach to the function. Motivated from that answer, I tried to implement the function in Python. I don't have any experience in numerical methods but I really like these kind of coding.

So here is my code:

# Precision is set to 50.
def f(k, x):
    if (k < 1):
        # First argument cannot be less than one.
        return -1
    try:
        temp = 1
        for i in xrange(k):
            temp = (k-i)*(x**temp)
        return temp
    except TypeError:
        # k should be an integer.
        return -1

Now I'm calling the function for k = 4 and x = 0.5 and I'm comparing my function's output with WolframAlpha's output. Here are the results:

0.43854381197983005602480943707632832229137420654297 <-- My output
0.43854381197983004379857027951312617339018977615169 <-- WolframAlpha's output

As you can see, after some point, the ouputs are very different. It's not a very big difference but still enough to make me curious.

  • Why is this happening?
    For this part, this one is helpful and I've already seen it months ago, so I'm a little aware of floating number behaviour but I wasn't sure that was the reason in my case when I posted my question in the first place. I will still need help for the following ones anyway.
  • Is my function not working properly?
    • If so, how should I fix it?
    • If it's OK, which result is more precise?
    • How can I optimize my code?
Community
  • 1
  • 1
Motun
  • 2,149
  • 3
  • 16
  • 23
  • What do you mean by "Precision is set to 50."? How do you think you did that? There's no way to set Python's floating-point precision. (Also, 50 what?) – user2357112 Dec 29 '15 at 23:28
  • @user2357112 I was using Anaconda's Scientific Python Development Environment (namely Spyder) which has IPython integrated, and IPython has a _magic command_ `precision`. When I type, for instance, `precision 50`, it's set that the output will be up to 50 decimal numbers after the point. – Motun Dec 29 '15 at 23:35
  • 1
    That says "Set floating point precision **for pretty printing**". It doesn't actually give you more precision for computation; you need an arbitrary-precision math library for that. `gmpy` or the built-in `decimal` module would be reasonable choices. – user2357112 Dec 29 '15 at 23:39
  • @user2357112 So are you saying IPython's `precision` command is the reason for that difference? – Motun Dec 29 '15 at 23:42
  • No, the difference is because Wolfram Alpha is using arbitrary-precision math and you're not. – user2357112 Dec 29 '15 at 23:47

0 Answers0