Home > Mobile >  Python calculate area of circle from two given points A and B
Python calculate area of circle from two given points A and B

Time:09-27

new to Python and programming in general. First homework and a little stumped on this question.

Given two points A(x1, y1) and B(x2, y2) in the plane. Write a program to calculate the area of a circle centered as A and go through B. Hint: The radius of the circle will be the distance between A and B. AB2 = ((x1 – x2)2 (y1 – y2)2). R = AB2 ** 0.5.

I am using PyCharm community edition and python latest version

CodePudding user response:

This is more of a basic math problem not realy a code problem but anyway:

PI=3.14

pointa={"x1":1,"y1":1}
pointb={"x2":2,"y2":2}
r=((pointa['x1']-pointb['x2'])**2  (pointa['y1']-pointb['y2'])**2)**0.5
area=PI*(r**2)

print(area)

replace the x1,x2,y1,y2 values as you wish in the pointa and pointb dictionaries

CodePudding user response:

Area if a circle is A = ∏ * r^2 and the distance between 2 points is found as d = √[(x2 − x1)^2 (y2 − y1)^2]

Knowing this, a Python implementation would be the following:

import math 

# Pi is a constant
PI = math.pi

# Distance between the 2 points (diameter)
d = math.sqrt(math.pow(x2 − x1, 2)   math.pow(y2 − y1, 2))

# Radius is half of the diameter
r = d/2

# A = ∏ * r^2
A = PI * math.pow(r, 2)

CodePudding user response:

Python includes direct support for complex numbers, which makes the radius calculation much easier.

import math

A = complex(1, 1)  # x1, y1
B = complex(2, 3)  # x2, y2

radius = abs(A - B)
area = math.pi*radius**2
  • Related