Diego Pujols
Diego Pujols

Reputation: 39

Calculates the width of a rectangle given the area and perimeter

Ive based the e1 and e2 sections of code as two halves of the google equation found when asking calculate width of a rectangle given perimeter and area.

This section of code is set to be part of a larger piece that displays the calculated rectangle in a visual form instead of using integers, however when i test it, the answer it gives is incorrect.

import math

print("Welcome to Rectangles! Please dont use decimals!")

area = int(input("What is the area? "))

perim = int(input("What is the perimeter? "))

e1 = int((perim / 4)  + .25)
e2 = int(perim**2 - (16 * area))
e3 = int(math.sqrt(e2))

width = int(e1 * e3)
print(width)

 

Upvotes: 2

Views: 2753

Answers (4)

Evan Nowak
Evan Nowak

Reputation: 895

If you don't need to use this equation specifically, it'd be easier to just brute force it.

import math 

print("Welcome to Rectangles! Please dont use decimals!")

area = int(input("What is the area? "))

perim = int(input("What is the perimeter? "))

lengths = range(math.ceil(perim/4), perim/2)

for l in lengths:
    if l*(perim/2 - l) == area:
        print(l)

Upvotes: 2

Артем Носов
Артем Носов

Reputation: 226

Here is the fixed code :

import math

print("Welcome to Rectangles! Please dont use decimals!")
S = int(input("Area ")) 
P = int(input("Perim ")) 
b = (math.sqrt (P**2-16*S)+P) /4
a = P/2-b
print (a,b)

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 191711

It's recommended you name your variables better so we know what you're trying to calculate.

From the Google formula, you should just translate it directly.

import math 

def get_width(P, A):
  _sqrt = math.sqrt(P**2 - 16*A)
  width_plus = 0.25*(P + _sqrt)
  width_minus = 0.25*(P - _sqrt)
  return width_minus, width_plus

print(get_width(16, 12)) # (2.0, 6.0)
print(get_width(100, 40)) # (0.8132267551043526, 49.18677324489565)

You get zero because int(0.8132267551043526) == 0

Important note: Your calcuation doesn't check

area <= (perim**2)/16

Upvotes: 2

Serjik
Serjik

Reputation: 10931

import math

print("Welcome to Rectangles! Please dont use decimals!")

area = int(input("What is the area? "))

perim = int(input("What is the perimeter? "))

e1 = int((perim / 4)  + .25)
e2 = abs(perim**2 - (16 * area))
e3 = math.sqrt(e2)

width = e1 * e3
print(width)

Upvotes: 1

Related Questions