rise over run slope calculator that outputs to feet and inches

Here is the starting code for a solution. What it does is calculates the slope then rounds. I think what you have is trying to use the Pythagorean theorem in some way, but it can be done much simpler by doing (deltaY) / (deltaX), or rise/run.

The rounding is done by multiplying the current value by 16, rounding to the nearest integer, then dividing by 16 again. Why this works is because of how fractions convert to decimals. If you multiply and you get an integer, then you know that you got a multiple of 1/16. If not, you need to round. The way to round is to go to the nearest 1/16 value. This is done normally by going seeing between which two values the number to round resides. If it is halfway to the higher number, you round to that, otherwise you round to the lower number. This does this principle, but instead of checking between which two it is between, it only checks the numerator essentially.

For example, if you have 5/32, that number is between 2/16 and 3/16. 5/32 * 16 is 5/2 or 2.5. 2.5 is closer to 3 so we round the value to that. Then we divide the answer by 16 to get 3/16 as the final result.

One more thing, it seems you were using sys.exit() to reach the end of the function. This can be done more easily by simply breaking out of the while loop using “break.”

A final thing, the state the program is in now does not check for a vertical line (if the bottom measurement is 0). I am not sure if this is a requirement, but you might have to check for that. In addition, I assumed that the rise is inputted first, then the run, making a = rise and b = run.

import math

def round1_16th(n):
    n *= 16
    n = round(n)
    return n/16

while (1): 
    print ("Enter the rise and run in inches to calculate slope.") 
    a = (input("First measurement is: ")) 
    if (a == "stop"): 
        print ("goodbye") 
    a= float (a)
    b = float (input("second measurement is: "))
    hyp = math.sqrt(a*a + b*b)
    hypInt = int(hyp)
    hypDec = hyp - hypInt
    numerator = round(hypDec*16)
    if hypInt == 0:
        hypInt = ""
    print ("Slope is:", round1_16th(hyp),"or",hypInt,str(numerator)+"/16th")

Browse More Popular Posts

Leave a Comment