Search code examples
pythonsympysymbolic-math

Finding roots of an equation involving a summation using sympy


I am currently to new to sympy and I am trying to reproduce the Mathematica example in the attached image in Python. My attempt is written below but it returns an empty listenter image description here

import sympy


m , n, D_star, a, j =  sympy.symbols('m , n, D_star, a, j')

s1 = sympy.Sum(a**(j-1),(j, 1, m-1))

rhs = 6 * sympy.sqrt((D_star * (1 + a)*(n - 1))/2)

expand_expr = sympy.solve(s1 - rhs, m) 

temp = sympy.lambdify((a, n, D_star), expand_expr, 'numpy')

n = 100
a = 1.2
D_star = 2.0

ms = temp(1.2, 100, 2.0)
ms

# what I get is an empty list []

# expected answer using Mma FindRoot function is 17.0652

Solution

  • Adding .doit() to expand the sum seems to help. It gives Piecewise((m - 1, Eq(a, 1)), ((a - a**m)/(1 - a), True))/a for the sum in s1.

    from sympy import symbols, Eq, Sum, sqrt, solve, lambdify
    
    m, n, j, a, D_star = symbols('m n j a D_star')
    
    s1 = Sum(a**(j - 1), (j, 1, m - 1)).doit()
    
    rhs = 6 * sqrt((D_star * (1 + a) * (n - 1)) / 2)
    
    expand_expr = solve(Eq(s1, rhs), m)
    
    temp = lambdify((a, n, D_star), expand_expr, 'numpy')
    
    n = 100
    a = 1.2
    D_star = 2.0
    
    ms = temp(1.2, 100, 2.0)
    

    This gives for expand_expr:

    [Piecewise((log(a*(3*sqrt(2)*a*sqrt(D_star*(a*n - a + n - 1)) - 3*sqrt(2)*sqrt(D_star*(a*n - a + n - 1)) + 1))/log(a), Ne(a, 1)), (nan, True)),
     Piecewise((3*sqrt(2)*a*sqrt(D_star*(a*n - a + n - 1)) + 1, Eq(a, 1)), (nan, True))]
    

    which separates into a != 1 and a == 1.

    The result of ms gives [array(17.06524172), array(nan)], again in a bit awkward way to separate a hypothetical a == 1.