不明白为什么这不会产生斜率为1和角度为45的直线

2024-09-30 06:34:30 发布

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

from matplotlib import pyplot as plt
import numpy as np

# Python program for slope of line
def slope(x1, y1, x2, y2):
    return (float)(y2-y1)/(x2-x1)

midPoint = 400
tenPercentOfMidpoint = .10 * midPoint

x = np.linspace(midPoint - tenPercentOfMidpoint, midPoint + tenPercentOfMidpoint, 50)
m = np.empty(x.shape)
c = np.empty(x.shape)

m[(x>=midPoint)] = 1.0
m[(x<midPoint)] = 1.0
c[x<midPoint] = 0
c[x>=midPoint] = 0

y=m*x+c

lenOfx = len(x)
lenOfy = len(y)
s = slope(0, y[0], lenOfx, y[lenOfy - 1])
angle = np.rad2deg(np.arctan2(x[-1] - x[0], lenOfy - 0))

如果我现在打印s

print(s)

结果是1.6

如果我打印angle

print(angle)

结果是57.99

我想在midPoint - tenPercent and midPoint + tenPercentslope45之间画一条线


Tags: importasnpslopeemptyx1x2shape
2条回答

我相信这只是一个插错东西的问题。您在slope中测试的点是(0, y[0])==(0, 360.0)(lenOfx, y[lenOfy - 1])=(50, 440.0)这些点不在y=m*x+c定义的线上。我相信您希望拉动线段的两个端点:

>>> slope(x[0], y[0], x[-1], y[-1]) # (360.0, 360.0, 440.0, 440.0)
1.0

计算角度的类似问题;您希望使用y中的更改和x中的更改:

>>> np.rad2deg(np.arctan2(y[-1] - y[0], x[-1] - x[0]))
45.0

坐标数(len)不应与坡度计算相关

注意xy是相同的(x == y返回True的向量)

对于坡度为1的直线,y的变化应与x的变化相同,即根据坡度的定义

I want a line between midPoint - tenPercent and midPoint + tenPercent that has slope 1 and angle 45

最接近坡度1线的方法是更改x

x = np.linspace(midPoint - tenPercentOfMidpoint, midPoint + tenPercentOfMidpoint, int(2*tenPercentOfMidpoint))

或者通过将百分之十的中点更改为一个数字

2*tenPercentOfMidpoint=50  ## because you mentioned 50 in np.linspace
tenPercentOfMidpoint=25

相关问题 更多 >

    热门问题