Skip to content

How to Calculate the area of a regular N sides polygon inside a circle of radius R in Python

The challenge

Write the following function:

def area_of_polygon_inside_circle(circle_radius, number_of_sides):
Code language: Python (python)

It should calculate the area of a regular polygon of numberOfSidesnumber-of-sides, or number_of_sides sides inside a circle of radius circleRadiuscircle-radius, or circle_radius which passes through all the vertices of the polygon (such a circle is called circumscribed circle or circumcircle). The answer should be a number rounded to 3 decimal places.

Input/Output Examples

area_of_polygon_inside_circle(3, 3) # returns 11.691 area_of_polygon_inside_circle(5.8, 7) # returns 92.053 area_of_polygon_inside_circle(4, 5) # returns 38.042
Code language: Python (python)

The solution in Python code

Option 1:

from math import sin, pi def area_of_polygon_inside_circle(r, n): return round(0.5 * n * r ** 2 * sin(2 * pi / n), 3)
Code language: Python (python)

Option 2:

import math def area_of_polygon_inside_circle(circle_radius, number_of_sides): r = circle_radius s = number_of_sides a = (s * (r ** 2) * math.sin(2*math.pi/s))/2 return round(a, 3)
Code language: Python (python)

Option 3:

from math import sin,cos,radians def area_of_polygon_inside_circle(circle_radius, number_of_sides): angle = radians(360/(number_of_sides*2)) opposite = circle_radius*sin(angle) adjacent = circle_radius*cos(angle) return round(adjacent*opposite*number_of_sides,3)
Code language: Python (python)

Test cases to validate our solution

test.describe('Example Tests') test.it('ex1') test.assert_equals(area_of_polygon_inside_circle(3, 3), 11.691) test.it('ex2') test.assert_equals(area_of_polygon_inside_circle(2, 4), 8) test.it('ex3') test.assert_equals(area_of_polygon_inside_circle(2.5, 5), 14.86)
Code language: Python (python)

See also  python "AttributeError: ZipFile instance has no attribute '__exit__"
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x