2014-09-21 119 views
0

所以我對python很陌生,但已經成功地創建了可以計算面積,體積,將攝氏度轉換爲華氏度等的程序......但是,我似乎遇到了一些麻煩用這個'斜線'程序。Python程序告訴你一條線的斜率

# A simple program which prompts the user for two points 
# and then computes and prints the corresponding slope of a line. 

# slope(S): (R*R)*(R*R) -> R 
# If R*R is a pair of real numbers corresponding to a point, 
# then slope(S) is the slope of a line. 
def x1(A): 
    def y1(B): 
     def x2(C): 
      def y2(D): 
       def slope(S): 
        return (D-B)/(C-A) 

# main 
# Prompts the user for a pair of points, and then computes 
# and prints the corresponding slope of the line. 

def main(): 
    A = eval(input("Enter the value of x1:")) 
    B = eval(input("Enter the value of y1:")) 
    C = eval(input("Enter the value of x2:")) 
    D = eval(input("Enter the value of y2:")) 
    S = slope(S) 
    print("The slope of a line created with those points\ 
is: {}{:.2f}".format(S,A,B,C,D)) 

main() 
+2

嘗試一個函數有四個參數,而不是與每一個論辯的四個*嵌套*功能https://docs.python.org/2.7/tutorial/controlflow.html#defining-functions – wwii 2014-09-21 03:04:55

回答

6

斜率功能可以像下面這樣 - 一個功能以代表這兩個點的四個座標四個參數:

def slope(x1, y1, x2, y2): 
    return (y1 - y2)/(x1 - x2) 

但很明顯,它不應該是這個簡單,你必須細化它並考慮x1 == x2的情況。

+3

的約定是。通常是'(y2 - y1)/(x2 - x1)'#nitpicking – 2014-09-21 03:18:10

+2

這並不重要,兩點是對稱的,因爲斜率是一個標量而不是矢量。只要你有相同的分子和分母的順序,就是對的。但是,如果你切換它們,並且有(y2-y1)/(x1-x2)這樣的東西 - 那就錯了。 – 2014-09-21 03:21:28

0

坡度=上升/運行。這是一個非常簡單的解決方案: - 用x和y成員創建一個類點。 - 創建一個方法getSlope,它將兩個點作爲參數 - 使用它們的x和y座標實例化兩個點變量。 - 打印結果(在這種情況下是getSlope方法的返回值

class Point: 
    def __init__ (self, x, y): 
     self.x = x 
     self.y = y 

# This could be simplified; more verbose for readability  
def getSlope(pointA, pointB): 
    rise = float(pointA.y) - float(pointB.y) 
    run = float(pointA.x) - float(pointB.x) 
    slope = rise/run 

    return slope 


def main(): 
    p1 = Point(4.0, 2.0) 
    p2 = Point(12.0, 14.0) 

    print getSlope(p1, p2) 

    return 0 

if __name__ == '__main__': 
    main() 
0

如果你想從兩個數組猜測最適合的斜率,這是最教科書的答案,如果X和Y是數組:

import numpy as np 
from __future__ import division 

x = np.array([1,2,3,4] 
y = np.array([1,2,3,4]) 
slope = ((len(x)*sum(x*y)) - (sum(x)*sum(y)))/(len(x)*(sum(x**2))-(sum(x)**2)) 
相關問題