Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematica to Python

How can this Mathematica code be ported to Python? I do not know the Mathematica syntax and am having a hard time understanding how this is described in a more traditional language.

mathematica code

Source (pg 5): http://subjoin.net/misc/m496pres1.nb.pdf

like image 450
Eric Schoonover Avatar asked Oct 18 '10 06:10

Eric Schoonover


People also ask

Can you use Python in Mathematica?

The Mathematica function ExternalEvalute lets you call Python from Mathematica.

Can Python replace Mathematica?

Python has numerous advantages over Mathematica. It is open source, and so it is more transparent. When something goes wrong, you can dig in and debug it.

Does Wolfram use Python?

The Wolfram Client Library for Python lets Python programs directly integrate Wolfram Language capabilities. Connect either to a local Wolfram Engine or to the Wolfram Cloud (or a private Wolfram Cloud).

What language is Mathematica coded in?

The Wolfram Language is the programming language used in Mathematica.


2 Answers

This cannot be ported to Python directly as the definition a[j] uses the Symbolic Arithmetic feature of Mathematica.

a[j] is basically the coefficient of xj in the series expansion of that rational function inside Apart.

Assume you have a[j], then f[n] is easy. A Block in Mathematica basically introduces a scope for variables. The first list initializes the variable, and the rest is the execution of the code. So

from __future__ import division
def f(n):
  v = n // 5
  q = v // 20
  r = v % 20
  return sum(binomial(q+5-j, 5) * a[r+20*j] for j in range(5))

(binomial is the Binomial coefficient.)

like image 57
kennytm Avatar answered Oct 07 '22 15:10

kennytm


Using the proposed solutions from the previous answers I found that sympy sadly doesn't compute the apart() of the rational immediatly. It somehow gets confused. Moreover, the python list of coefficients returned by *Poly.all_coeffs()* has a different semantics than a Mathmatica list. Hence the try-except-clause in the definition of a().

The following code does work and the output, for some tested values, concurs with the answers given by the Mathematica formula in Mathematica 7:

from __future__ import division
from sympy import expand, Poly, binomial, apart
from sympy.abc import x

A = Poly(apart(expand(((1-x**20)**5)) / expand((((1-x)**2)*(1-x**2)*(1-x**5)*(1-x**10))))).all_coeffs()

def a(n):
    try:
        return A[n]
    except IndexError:
        return 0

def f(n):
    v = n // 5
    q = v // 20
    r = v % 20
    return sum(a[r+20*j]* binomial(q+5-j, 5) for j in range(5))

print map(f, [100, 50, 1000, 150])
like image 44
nanitous Avatar answered Oct 07 '22 17:10

nanitous