'Expression not converting to float

I'm beginner in python:(

This is my code and I got an error message 'can't convert expression to float'.

import numpy as np
import sympy as sp
from sympy import symbols,diff
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)
x,y=symbols('x,y')
f=2/((x+2*y)**2+4)
dfdx=diff(f,x)
dfdy=diff(f,y)
ddfddx=diff(dfdx,x)
ddfddy=diff(dfdy,y)
z=ddfddy
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, projection='3d')
plt.plot(x,y,z)


Solution 1:[1]

You need to be careful here about the difference between floats and sympy algebraic expression types. Objects are of a type; that type tells you what the object can do. Specifically, there are a set of functions associated with a specific object known as "methods" and some functions can only work with specific objects. plt.plot() is expecting a set of numbers. So, it is expecting that you give it array objects composed of elements of type int (integers) or float (real numbers rounded to some large decimal value); both of these types come prebuilt in Python. The package Sympy has its own types associated with algebraic expressions. This package allows for symbolic algebra in Python - it's quite similar to the Mathematica language.

Here is a solution to the problem:

import numpy as np
import sympy as sp
from sympy import symbols, diff, lambdify
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)
xs, ys = symbols('x,y')
fs = 2/((xs+2*ys)**2+4)
dfdx=diff(fs,xs)
dfdy=diff(fs,ys)
ddfddx=diff(dfdx,xs)
ddfddy=diff(dfdy,ys)
zs=ddfddy
f = lambdify([xs,ys],zs)
z = f(x,y)

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, projection='3d')

print(type(xs),type(ys))
print(type(x),type(y),type(z))
plt.plot(x,y,z)
plt.show()

The only differences here are that I renamed the symbol types as xs, ys, and zs while leaving x, y, and z as the arrays of floats. I also had to add a sympy function called lambify which takes the symbolic expression zs and turns it into a function f which I then evaluate for the set of points x, y to get z.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Didymus Prime