0

I have working code using sympy.lambdify for a user input function string and then to plot the function. It fails if the function entered is just a constant number.

The code I am using is

import sympy as sy
import numpy as np
import matplotlib.pyplot as plt

x = sy.symbols('x')
func = 5
x_range = np.linspace(0, 10, 100)
F = sy.lambdify(x, func, "numpy")
y_range = F(x_range)
plt.plot(x_range, y_range)

So if func is a valid function like "2x" or "sin(x) - 7x**2", the code works fine.

However, if I enter a constant, say "5", I get a single number in y_range, not an array like x_range with all elements equal to the value of the entered constant. Therefore, I get a value error

ValueError: x and y must have same first dimension, but have shapes (200,) and (1,)

I have played with this for so long, I am beginning to feel like it is an error or inconsistency in sympy.

Does any one have a suggestion please?

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
KitingPaul
  • 49
  • 5
  • Please show what `func` is when you get the error. If it just does `return 5`, why do you expect that `5` to magically turn into an array? To clarify, the `x` part of `"2x"` and `"sin (x)..."` is what makes it an array if `x` is an array – Pranav Hosangadi Jun 07 '22 at 12:35
  • Yes Pranav, I get that, but what if I want my function to be "0x + 5", which is what I want. (I have tried this, but it still does not work) – KitingPaul Jun 07 '22 at 12:42
  • @KitingPaul I must say disagree. I would expect the result of lambdify for a constant to be a *fuction* that returns this constant. – Jacques Gaudin Jun 07 '22 at 12:49
  • Yes, sadly that is true, I think it is inconsistent but I have tested for a constant and allowed for this option and it is working now. Thanks for everyone's help :) – KitingPaul Jun 07 '22 at 13:08
  • `help(F)` should show the python code. `lambdify` doesn't do a deep analysis; it's basically a lexical translator. – hpaulj Jun 07 '22 at 14:27
  • When you try to lambdify something like `expr = 0*x+5`, did you first look at `expr`? `sympy` has reduced that to `5`, so `lambdify` isn't getting anything different. I run `sympy` in an interactive session, not as a standalone script. I need to check intermediate values, results line by line. You could have avoided the plot error if you had looked at `yrange`. – hpaulj Jun 07 '22 at 15:21

0 Answers0