I\'m looking for a fast way to determine the area of intersection between a rectangle and a circle (I need to do millions of these calculations).
A specific property
The following is how to calculate the overlapping area between circle and rectangle where the center of circle lies outside the rectangle. Other cases can be reduced to this problem.
The area can be calculate by integrating the circle equation y = sqrt[a^2 - (x-h)^2] + k where a is radius, (h,k) is circle center, to find the area under curve. You may use computer integration where the area is divided into many small rectangle and calculating the sum of them, or just use closed form here.
And here is a C# source implementing the concept above. Note that there is a special case where the specified x lies outside the boundaries of the circle. I just use a simple workaround here (which is not producing the correct answers in all cases)
public static void RunSnippet()
{
// test code
double a,h,k,x1,x2;
a = 10;
h = 4;
k = 0;
x1 = -100;
x2 = 100;
double r1 = Integrate(x1, a, h, k);
double r2 = Integrate(x2, a, h, k);
Console.WriteLine(r2 - r1);
}
private static double Integrate(double x, double a,double h, double k)
{
double a0 = a*a - (h-x)*(h-x);
if(a0 <= 0.0){
if(k == 0.0)
return Math.PI * a * a / 4.0 * Math.Sign(x);
else
throw new Exception("outside boundaries");
}
double a1 = Math.Sqrt(a*a - (h-x)*(h-x)) * (h-x);
double area = 0.5 * Math.Atan(a1 / ((h-x)*(h-x) - a*a))*a*a - 0.5 * a1 + k * x;
return area;
}
Note: This problem is very similar to one in Google Code Jam 2008 Qualification round problem: Fly Swatter. You can click on the score links to download the source code of the solution too.