割线太长,尽量不使用y限制

2024-03-29 12:44:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python来教自己calc的基础知识

我使用matplotlib pyplot跟踪函数曲线,然后从指定的两个点(p1和p2)绘制一条割线。

我想我的大部分数学工作正常,但如果我不在Y轴上使用限制(曲线的Y.min,Y.max),那么割线有时会变得很长,并“压碎”我的曲线。

我只是不确定什么是限制直线的最佳数学方法,这样它就不会超出曲线的最大或最小y值:

未设置限制: No Y Limit

曲线的限制设置为(Y.min,Y.max): With Y Limit Set To Y.min,Y.max of curve

这里是我的代码:

import matplotlib.pyplot as plt
import numpy as np

ls = np.linspace(-2,2,100)
p1 = 2  #starts from zero
p2 = 50 #starts from zero

def draw_func(ls):
    x = ls
    y = x**2
    #y = (x**4-2*x**2+x)
    plt.plot(x,y)
    return y

x = ls
y = draw_func(ls)

x1 = x[p1]
x2 = x[p2]
y1 = y[p1]
y2 = y[p2]

m = (y2-y1) / (x2-x1)

delta_x = x2 - x1
delta_x = x1 + (delta_x/2)

b = y2 - y1
b = y1 + (b/2)

def draw_line(ls, m, b):
    x = ls
    y = (m * (x-delta_x)) + b
    plt.plot(x,y)

draw_line(ls, m, b)

plt.ylim(y.min(),y.max()) #This Is What I Was Hoping To Avoid

plt.show()

Tags: matplotlibpltminls曲线maxdeltax1
2条回答

你可以采取几种不同的方法。在

一种是只画出割线的一部分。你可以在任何地方计算它,过滤出比你的“主”曲线大得多或小得多的点,或者你可以计算一个更有限的范围来评估它。在

另一种方法是告诉matplotlib只对“主”曲线进行自动缩放,而对另一条曲线不设置限制。在


首先,我将以稍微不同的方式编写您的示例。你做事的方式没有错,但我觉得这种风格更具可读性:

import matplotlib.pyplot as plt
import numpy as np

def main():
    x = np.linspace(-2,2,100)
    p1 = 2  #starts from zero
    p2 = 50 #starts from zero

    y1 = main_func(x)
    y2 = calculate_secant(x, y1, p1, p2)
    plot(x, y1, y2)
    plt.show()

def main_func(x):
    return x**2

def calculate_secant(x, y, p1, p2):
    points = [p1, p2]
    m, b = np.polyfit(x[points], y[points], 1)
    return m * x + b

def plot(x, y1, y2):
    plt.plot(x, y1)
    plt.plot(x, y2)

main()

我们会得到一个“缩小”的图,你不想要:

enter image description here


如果稍微更改plot函数,我们可以告诉matplotlib在绘制第二条直线时不要更改轴限制:

^{pr2}$

enter image description here


或者,我们可以从绿线中屏蔽出明显大于蓝线的点(关键是下面的第三条线,其他线是相同的,并根据上下文给出:

y1 = main_func(x)
y2 = calculate_secant(x, y1, p1, p2)
y2[y2 < y1] = np.nan
plot(x, y1, y2)

这将产生(可能是不需要的,可能是期望的)副作用,即剪掉两条线交叉的左侧:

enter image description here

可以计算曲线顶点的坐标。从起点到x值绘制直线,而不是继续整个范围。在

相关问题 更多 >