简体   繁体   中英

Need help plotting and finding local maxima and minima in Python using sympy. first part works but can't figure out how to do the other parts

This is the assignment I'm working on here .

I am asked to use Python with the Sympy package to code it. I was able to get the right ouput for Part A.

import numpy as np
from numpy import linspace, math, arange, linspace
from sympy import *
import sympy as sp
import math

x = Symbol('x')
f = (x**(4/5)) * ((x-4)**2)   
fd = diff(f) #first derivative
fdd = diff(fd) #second derivative (for later)
print("f' =", fd)

print("Critical Vales are:")
dRoots = solve(Eq(fd, 0)) #finds critical values
print(dRoots)

I don't know how to code part B and C where it asks for the local maxima and minima and for the plot of f on the interval x ∈ [−1, 6] . What I have so far gives me a "'>' not supported between instances of 'list' and 'int'" error

fdd_val = solve(Eq(fdd, 0))
if fdd_val > 0:
    print("Local Maxima = ",fdd_val)
if fdd_val < 0:
    print("Local Minima = ",fdd_val)

Generally speaking, we try to steer clear of posting homework questions on SO, but since you took a genuine attempt at doing the problem, I'll offer some tips and corrections to your code.

from sympy import *
# Optimize imports -> if you don't need it, don't include it

x = Symbol('x')
f = (x**(4/5)) * ((x-4)**2)   
fd = diff(f) #first derivative

# pick more descriptive variable names: you'll thank yourself later. Like 'second_derivative' or even 'sd'
fdd = diff(fd) #second derivative (for later)
print("f' =", fd)

print("Critical Vales are:")

# call solve on fd like the documentation suggests.
dRoots = solve(fd) #finds critical values, returns a list
print(dRoots, '\n')
for root in dRoots:
    # Use function.subs(variable, value) to evaluate d2/dx^2 [f(x)] at each critical point
    fdd_val = fdd.subs(x, root)
    print(f"At root {root:.5g}, second derivative at this point is {fdd_val:.5g} which is "
          f"{'less' if fdd_val < 0 else 'greater'} than zero, so this is a local _____")

This revised code should point out the right way to evaluate expressions according to the documentation , as well as give you some insight on how to proceed. You should be able to finish up from here. Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM