Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of the intersecting part in a circle in Java

I need the size of the black part of this image:
Image

I've done some research about how to find it in normal math, and I was pointed to this website: Website

The final answer on getting it was pict
(from MathWorld - A Wolfram Web Resource: wolfram.com)

where r is the radius of the first circle, R the radius of the second circle, and d the distance between the two centers.

The code I tried to use to get the size of this was the following:

float r = getRadius1();
float R = e.getRadius1();
float deltaX = Math.abs((getX()  + getRadius()) - (e.getX() + e.getRadius()));
float deltaY =  Math.abs((getY()  + getRadius()) - (e.getY() + e.getRadius()));
float d = (float) Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));

float part, part2, part3;
//Chopping it in parts, because it's easier.

part = (float) (Math.pow(r,2) * Math.acos(
      Math.toRadians((Math.pow(d, 2) + Math.pow(r, 2) - Math.pow(R, 2))/(2*d*r))));

part2 = (float) (Math.pow(R,2) * Math.acos(
      Math.toRadians((Math.pow(d, 2) + Math.pow(R, 2) - Math.pow(r, 2))/(2*d*R))));

part3 = (float) (0.5 * Math.sqrt((-d + r + R) * (d+r-R) * (d-r+R) * (d+r+R)));

float res = part + part2 - part3; 

Main.log(res + "       " + part + " " + part2 + " " + part3+ "       "
         + r + " " + R  + " " + d);
//logs the data and System.out's it

I did some testing, and the output was this:

1345.9663       621.6233 971.1231 246.78008       20.0 25.0 43.528286

So that indicates that the size of the overlapping part was bigger than the circle itself (which is r^2 * PI).

What did I do wrong?

like image 402
Lolmewn Avatar asked Jan 10 '12 16:01

Lolmewn


1 Answers

Just a guess (as stated in my comment): try removing the Math.toRadians(...) conversion.

Since there are no degrees involved in the formula but rather radii, I assume the parameter to cos-1(...) is already a value in radians.

If I remove the conversion and run your code, I get the following overlap area size: 11.163887023925781 which seems plausible since the length of the overlap segment on the line between the two centers is 20 + 25 - 43.5 = 1.5 (approximated)

Edit:

If I set the distance to 5 (the smaller circle is completely contained in the bigger one but touches its edge) I get the overlap area size 1256.63 which is exactly the area of the smaller circle (202 * Π). The calculation doesn't seem to work if the distance is smaller than the difference of the radii (i.e. in your case smaller than 5), but that might just be a problem of numerical representation (the normal datatypes might not be able to represent some of the intermediate results).

like image 186
Thomas Avatar answered Oct 04 '22 06:10

Thomas