我必须制作一个带有函数,其导数和切线的图形。 我正在使用Bokeh库在python上锻炼。
我尝试了多种计算方法来求切线。要更改变量,功能但没有成功。
import numpy as np
from bokeh.layouts import row, widgetbox
from bokeh.models import CustomJS, Slider
from bokeh.plotting import figure, output_file, show, ColumnDataSource
#First Curve
x = np.linspace(-10, 10)
a = -10
y = (x**3)-12*x
#fonction
def f(x):
return ((x**3)-12*x)
def fprime(x):
return ((3*x**2)-12)
yprime = fprime(x)
#prepare list of value for tan
ytan = []
yprimetan = []
tan = []
for a in range (-25,25):
y1 = f(a)
y2= fprime(a)
y3 = y1 * a + y2
ytan.append(y1)
yprimetan.append(y2)
tan.append(y3)
print('liste y ',ytan)
print('liste yprime ',yprimetan)
print('liste tan ',tan)
source = ColumnDataSource(data=dict(x=x,y=ytan))
plot = figure(y_range=(-50, 50), plot_width=800, plot_height=800)
plot.line('x','y', source=source, line_width=3,legend= 'Fonction', line_alpha=0.6)
callback = CustomJS(args=dict(source=source), code="""
var data = source.data;
var A = amp.value;
var B = offset.value;
var x = data['x']
var y = data['y']
for (var i = -10; i < x.length; i++) {
y[i] = B + A *((x[i]**3)-12*x[i]);
}
source.change.emit();
""")
amp_slider = Slider(start=-10, end=10, value=1, step=.1,
title="Amplitude", callback=callback)
callback.args["amp"] = amp_slider
offset_slider = Slider(start=-10, end=10, value=0, step=.1,
title="Offset", callback=callback)
callback.args["offset"] = offset_slider
#Second Curve dérivé
source2 = ColumnDataSource(data=dict(x=x, y=yprimetan))
plot.line('x', 'y', source=source2, line_width=3,legend= 'Dérivé', line_alpha=0.6,color='red')
#Third Curve Tan
source3 = ColumnDataSource(data=dict(x=x,tan=tan,yprime=yprimetan,y=tan))
plot.line('x','tan', source=source3,legend= 'Tangente', line_width=3, line_alpha=0.6,color='green')
callback = CustomJS(args=dict(source=source3), code="""
var data = source.data;
var Z = tangente.value;
var y = data['y']
var yprime = data['yprime']
var tan = data['tan']
var x = data['x']
for (var i = -10; i < x.length; i++) {
tan[i] = yprime[i] * (x[i]-Z) + y[i] ;
}
source.change.emit();
""")
#tan[i]= (3*(x[i]**2)-12) * (Z-x[i]) + ((x[i]**3)-12*x[i])
tan_slider = Slider(start=-10, end=10, value=1, step=.1,
title="Tangente", callback=callback)
callback.args["tangente"] = tan_slider
#Output
layout = row(
plot,
widgetbox(amp_slider, offset_slider,tan_slider),
)
output_file("slider.html", title="slider.py example")
show(layout)
我希望有一条切线,我可以沿曲线移动。 您可以执行代码以查看当前的图形。