1

I get some trouble, if I want to pass a float to mpmath.mpf and find the root with mp.findroot.

The problem continues the story of a previous question: Polynomial function cannot be solved by Python sympy

import sympy
omega = sympy.symbols('omega')
from sympy import I 
import mpmath as mp
import numpy as np

# Definition of simplified function
def function(omega):
    return sympy.Poly((-1.16*omega**4), omega)

# This function does not work
def doesntwork(omega):
    return (mp.mpf(str(np.real(sympy.lambdify( (I),function(omega).coeffs()[0])(1j)))) * omega ** 4)

# This function does work, but I need to handover the value due to its not constant
def doeswork(omega):
    return (mp.mpf('-1.16') * omega ** 4)

#print mp.findroot(doesntwork, 1)   # error message
print mp.findroot(doeswork, 1)      # result is obtained

The mp.findroot command does work if I enter the coefficient with a string, but does not work if I read the coefficient by an automatic procedure. The problem seems to be caused by the input to mpmath.mpf which is not recognized as string. I need this automatic procedure, because the coefficients are not constant as in this simple example.

The error message for the function doesntwork is:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-44-7ed2fe96e32b> in <module>()
----> 1 print mp.findroot(doesntwork, 1)   # error message
      2 #print mp.findroot(doeswork, 1)      # result is obtained

C:\Anaconda\lib\site-packages\mpmath\calculus\optimization.pyc in findroot(ctx, f, x0, solver, tol, verbose, verify, **kwargs)
    926         # detect multidimensional functions
    927         try:
--> 928             fx = f(*x0)
    929             multidimensional = isinstance(fx, (list, tuple, ctx.matrix))
    930         except TypeError:

<ipython-input-40-f85df4161c52> in doesntwork(omega)
      1 # This function does not work
      2 def doesntwork(omega):
----> 3     return (mp.mpf(str(np.real(sympy.lambdify( (I),function(omega).coeffs()[0])(1j)))) * omega ** 4)
      4 
      5 # This function does work, but I need to handover the value due to its not constant

<ipython-input-39-fb50e638fea4> in function(omega)
      1 # Definition of simplified function
      2 def function(omega):
----> 3     return sympy.Poly((-1.16*omega**4), omega)

C:\Anaconda\lib\site-packages\sympy\polys\polytools.pyc in __new__(cls, rep, *gens, **args)
     71     def __new__(cls, rep, *gens, **args):
     72         """Create a new polynomial instance out of something useful. """
---> 73         opt = options.build_options(gens, args)
     74 
     75         if 'order' in opt:

C:\Anaconda\lib\site-packages\sympy\polys\polyoptions.pyc in build_options(gens, args)
    729 
    730     if len(args) != 1 or 'opt' not in args or gens:
--> 731         return Options(gens, args)
    732     else:
    733         return args['opt']

C:\Anaconda\lib\site-packages\sympy\polys\polyoptions.pyc in __init__(self, gens, args, flags, strict)
    152                     self[option] = cls.preprocess(value)
    153 
--> 154         preprocess_options(args)
    155 
    156         for key, value in dict(defaults).items():

C:\Anaconda\lib\site-packages\sympy\polys\polyoptions.pyc in preprocess_options(args)
    150 
    151                 if value is not None:
--> 152                     self[option] = cls.preprocess(value)
    153 
    154         preprocess_options(args)

C:\Anaconda\lib\site-packages\sympy\polys\polyoptions.pyc in preprocess(cls, gens)
    290         elif has_dups(gens):
    291             raise GeneratorsError("duplicated generators: %s" % str(gens))
--> 292         elif any(gen.is_commutative is False for gen in gens):
    293             raise GeneratorsError("non-commutative generators: %s" % str(gens))
    294 

C:\Anaconda\lib\site-packages\sympy\polys\polyoptions.pyc in <genexpr>((gen,))
    290         elif has_dups(gens):
    291             raise GeneratorsError("duplicated generators: %s" % str(gens))
--> 292         elif any(gen.is_commutative is False for gen in gens):
    293             raise GeneratorsError("non-commutative generators: %s" % str(gens))
    294 

AttributeError: 'mpf' object has no attribute 'is_commutative'

Thank you for your help!

Community
  • 1
  • 1
Aloex
  • 103
  • 8

1 Answers1

0

I solved the problem. Obviously, it is different if the coefficient is stored in a variable before.

coefficient = str(np.real(sympy.lambdify( (I),function(omega).coeffs()[0])(1j)))
def doesntwork(omega):
    return (mp.mpf(coefficient) * omega ** 4)

print mp.findroot(doesntwork, 1) 

Output

0.00267117593442144 
Aloex
  • 103
  • 8