I'm making a program that uses derivates to calculate an error.

I keep getting this error : 'Mul' object has no attribute 'sp'.

The solutions to this error that i've found so far are when people import everything from sympy and math (from sympy/math import *) because both sympy and math have a sin() function.

But as you can see from my code bellow i don't have it like that and the error still shows up, why?

import sympy as sp
from math import factorial

def F(x):
  return 4*(x**2)+sp.sin(9*x)

sp.init_printing()
x=sp.symbols('x')
def D1(x1):
  return(sp.diff(F(x),x,1).sp.subs(x,x1))

def D2(x1):
  return(sp.diff(F(x),x,2).sp.subs(x,x1))

def D3(x1):
  return(sp.diff(F(x),x,3).sp.subs(x,x1))

def maxD3(x1,x2):
  if(D3(x1)>D3(x2)):
    return D3(x1)
  else:
    return D3(x2)

erro1 = (1/factorial(3))*maxD3(-1,1)*abs((0.3-(-1))*(0.3-1))
erro1 = (1/factorial(3))*maxD3(-1,1)*abs((0.83-(-1))*(0.83-1))

print("Erro f(0.3): ", erro1)
print("Erro f(0.83): ", erro2)

Also have changed "from math import factorial" to "import math as math" and the error also keeps showing up.

I'm using Python 3.6.1.

EDIT: Full Traceback

Traceback (most recent call last):
  File "main.py", line 24, in <module>
    erro1 = (1/math.factorial(3))*maxD3(-1,1)*abs((0.3-(-1))*(0.3-1))
  File "main.py", line 19, in maxD3
    if(D3(x1)>D3(x2)):
  File "main.py", line 16, in D3
    return(sp.diff(F(x),x,3).sp.subs(x,x1))
AttributeError: 'Mul' object has no attribute 'sp'

1 Answers

0
Supreet Agrawal On

This is the corrected version of your code

import sympy as sp
from math import factorial

def F(x):
  return 4*(x**2)+sp.sin(9*x)

sp.init_printing()
x=sp.symbols('x')
def D1(x1):
  return(sp.diff(F(x),x,1).subs(x,x1)) # subs instead of sp.subs

def D2(x1):
  return(sp.diff(F(x),x,2).subs(x,x1)) # subs instead of sp.subs

def D3(x1):
  return(sp.diff(F(x),x,3).sp.subs(x,x1))

def maxD3(x1,x2):
  if(D3(x1)>D3(x2)):
    return D3(x1)
  else:
    return D3(x2)

erro1 = (1/factorial(3))*maxD3(-1,1)*abs((0.3-(-1))*(0.3-1))
erro2 = (1/factorial(3))*maxD3(-1,1)*abs((0.83-(-1))*(0.83-1)) # erro2 instead of erro1

print("Erro f(0.3): ", erro1)
print("Erro f(0.83): ", erro2)

Output on my system:

('Erro f(0.83): ', 0)

('Erro f(0.83): ', 0)

Is this the expected output?

Also, you don't need to import everything from sympy. You can just import what you need. Example:

>>> from sympy import sin, symbols, diff
>>> x = symbols('x')
>>> f = x**3 + sin(x)
>>> print(diff(f, x))
3*x**2 + cos(x)
>>> print(diff(f, x).subs(x, 1))
cos(1) + 3