Area of intersecting circles
Triv Prasad Mar 8
A few days ago, my daughters wanted to know how to find out the bounded area of two intersecting circles. This program is an attempt to teach them both Trigonometry as well as computer science. We started off doing only the basic condition when both circles play nice and intersect with the distance between centers parallel to the horizontal axis. Slowly, we extended the code to cater for other cases where the circles only touch at one point, may not touch at all or one circle is completely inside the other circle.
Basically, the input takes three parameters -> the distance between the centers of the two circles and the radii of the two circles in question. The common area is the output of the program.
Looking for ways to make this a more optimal program as I'm new to python.
import sys import math # Return the area of the smaller circle def smallercirclearea(r1, r2): radsmaller = min(r1, r2) return math.pi * radsmaller * radsmaller def calcAreaIntersectingCircles(d, rad1, rad2): rad1sqr = rad1 * rad1 rad2sqr = rad2 * rad2 #if the circle centers are the same if d == 0: print ('\nCircles have the same center. Intersecting area will be area of smaller circle') return smallercirclearea(rad1,rad2) angle1 = (rad1sqr + (d * d) - rad2sqr) / (2 * rad1 * d) angle2 = (rad2sqr + (d * d) - rad1sqr) / (2 * rad2 * d) # Check to see if the circles are overlapping if ((angle1 < 1 and angle1 >= -1) or (angle2 < 1 and angle2 >= -1)): theta1 = (math.acos(angle1) * 2) theta2 = (math.acos(angle2) * 2) area1 = (0.5 * theta2 * rad2sqr) - (0.5 * rad2sqr * math.sin(theta2)) area2 = (0.5 * theta1 * rad1sqr) - (0.5 * rad1sqr * math.sin(theta1)) return area1 + area2 elif angle1 == 1 and angle2 == 1: print ('\nCircles touch at a single degenerate point and do not intersect\n') return 0 elif angle1 < -1 or angle2 < -1: print('\nSmaller circle is completely inside the larger circle. Intersecting area will be area of smaller circle') return smallercirclearea(rad1,rad2) else: print ('\nImaginary touch points\n') return -1 #Read the distance and radii from the command line if len(sys.argv) == 4: distance = int(sys.argv) radiusCircle1 = int(sys.argv) radiusCircle2 = int(sys.argv) if distance < 0 or radiusCircle1 < 0 or radiusCircle2 < 0: print('Values cannot be negative. Goodbye') exit(1) print('\nThe intersecting area of the two circles is', round(calcAreaIntersectingCircles(float(distance), float(radiusCircle1), float(radiusCircle2)), 2), 'square units\n') else: print('\nNEED 3 VALUES IN THE INPUT!!\n') exit(1)
Git was invented by the Linux project in order to move beyond the crappy solutions they had in place before, and since then it has established itself as the de facto standard for version control and software collaboration.