Is there a way to assign values to symbolic variables after deriving them using sympy?

Asked

Viewed 37 times

2

Hello, I need to write a code that derives a user-informed function and then assign values to variables to perform the calculation. The problem is that it is necessary for the variables to be symbolic for the sympy to derive them and if they assume some numerical value, the sympy does not perform the derivation. Here’s what I’ve tried:

from sympy import diff, var

r, h = var('r h')

def derivadaVolume():
    volume = 3.14*(r**2)*h
    return diff(volume, h) 

h = 3    
r = 2
derivadaVolume()

The mistake: Valueerror: First variable cannot be a number: 3

However, if for example, I derive relative to r and assign value only to h:

from sympy import diff, var

r, h = var('r h')

def derivadaVolume():
    volume = 3.14*(r**2)*h
    return diff(volume, r) 

h = 3    
derivadaVolume()

Output: 18.84

I have also tried to assign a variable the derivative returned in the derivative function Volume() but when changing the values of r and h, nothing changes in the value of the variable:

from sympy import diff, var

r, h = var('r h')

def derivadaVolume():
    volume = 3.14*(r**2)*h
    return diff(volume, r) 
    
derivada = derivadaVolume()
h = 3
r = 2
derivada

Output: 6.28ℎ

Does anyone know if it is possible to solve this problem? Is there any other library that makes it able?

Thank you very much.

1 answer

2


from sympy import diff, var

r, h = var('r h')

def derivadaVolume():
    volume = 3.14*(r**2)*h
    return diff(volume, h) 

h = 3    
r = 2
derivadaVolume()

When you do that, you’re saying that h is worth 3 before calculating the derivative and when it is calculated you would be trying to derive relative to a constant, 3. This makes no sense and so gives error.

This problem you solved in the second attempt, where you calculated the derivative before assigning the values:

from sympy import diff, var

r, h = var('r h')

def derivadaVolume():
    volume = 3.14*(r**2)*h
    return diff(volume, r) 
    
derivada = derivadaVolume()
h = 3
r = 2
derivada

But it drifted in relation to r (I don’t understand why this has changed).

The point is that just assigning the value to a variable will not directly impact the value of the variable, as you imagined. You need to replace the values in the derivative:

resultado = derivada.subs({
  h: 3,
  r: 2
})

Thus, resultado shall, as indicated, be the value of derivada with the variables h and r replaced by 3 and 2 respectively.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.