Home > database >  Trying to calculate the maximum of a function but I do not get the right answer?
Trying to calculate the maximum of a function but I do not get the right answer?

Time:10-17

I am trying to calculate the maximum point of a function. My code is:

def S(t):
    return (10*sympy.E**(t/12)*((sympy.sin((sympy.pi*t)/24))**2))
sympy.plotting.plot(S(t), (t,0,24))
deriv = sympy.diff(S(t), t)
test = sympy.Eq(deriv, 0) 
deriv1 = sympy.Eq(sympy.diff(S(t), x), 0, sympy.Interval(10,20))
sympy.solveset(deriv1)

Afer, plotting it shows that the maximum should be around t=14. I tried several other methods:

expn = sympy.solveset(sympy.Eq(sympy.diff(S(t)), 0))
gfg  = expn.evalf()
sympy.pprint(gfg)

I also tried the following:

sympy.solveset(test)

I still do not get t=14. Does someone know what I am doing wrong?

CodePudding user response:

While solveset might returns a better formal solution, it is often difficult to manipulate it in order to get numerical values. This is one of those cases in which it is much better to use solve instead, and loop over its solutions to find the one you are looking for:

solutions = sympy.solve(sympy.Eq(S(t).diff(t), 0), t)
print(solutions)
# out: [0, 24, 48*atan((1 - sqrt(1   pi**2))/pi)/pi, 48*atan((1   sqrt(1   pi**2))/pi)/pi]

Note that the third and fourth solutions have not been evaluated:

[s.n() for s in solutions]
# out: [0, 24.0000000000000, -9.64576171314495, 14.3542382868550]

There you go, the last one is the solution you are looking for.

  • Related