Search code examples
pythonloopsrangesympyderivative

Including the calculation of a derivative in a loop


I am pretty new to Python. I wanted to code a loop which includes a derivative as well as other expressions (up until now I just have the derivative).

However, I get the error "First variable cannot be a number: 1". I think I am getting the error because Python tries to differentiate the function wrt to t but then a value for t is already specified because of the range function.

I do not know how to get around this error (especially as I think that the function and derivative would need to be in the loop for the other things I want to program).

## IMPORT PACKAGES
import numpy as np
import math
import sympy as sym
import matplotlib.pyplot as plt
from scipy import misc

## DEFINING THE SYMBOLS AND FUNCTIONS
t = sym.Symbol("t")
f_diff = sym.Function("f_diff")
f = sym.Function("f")

## LOOP WITH DERIVATIVE

for t in range (1,4,1):
    f = t**2
    f_diff = sym.diff(f, t)
    print(f_diff)


Solution

  • use evalf

    You are passing a value of variable instead of passing the variable. If you want to find derivative at some value then you can use evalf

    for i in range (1,4,1):
        f = t**2
        f_diff = sym.diff(f,t).evalf(subs={t: i})
        print(f_diff)
    

    2.00000000000000
    4.00000000000000
    6.00000000000000