题目
给定x1,y1,z1,r1,x2,y2,z2,r2,
求(x1,y1,z1)为圆心,r1为半径的球
和(x2,y2,z2)为圆心,r2为半径的球的体积并
思路来源
https://blog.csdn.net/luyehao1/article/details/86583384
https://blog.csdn.net/enterprise_/article/details/81624174
https://www.cnblogs.com/qingjiuling/p/10459877.html
题解
体积并=两球体积之和-球的体积交,那么代码ans就是求体积交
体积交,先讨论内含和外离的情形,
①内含,是小的那个球的体积
②外离,是0
③相交,先求出球缺的高度,然后对原球的球面片积分
显然,球的体积交是两个球缺的体积和,V=V1+V2
心得
其实我是不知道什么时候加eps什么时候不加,那就加着玩吧……
化简的时候能少除的少除,把式子化到最简减少精度误差
然后就是分类讨论和化简完的结果敲一敲代码吧……
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const double pi = acos(-1);
const double eps=1e-9;
const int MAX = 100 + 10;
const int inf = 1e9 + 7;
typedef struct {
double x, y, z, r;
}Point;
Point a;
Point s;
//两点之间距离
double dis(Point p, Point q) {
double ans = sqrt((p.x - q.x)*(p.x - q.x) + (p.y - q.y)*(p.y - q.y) + (p.z - q.z)*(p.z - q.z));
return ans;
}
double calV(Point p)
{
return (4.0/3)*pi*(p.r*p.r*p.r);
}
int main()
{
scanf("%lf%lf%lf%lf", &a.x, &a.y, &a.z, &a.r);
scanf("%lf%lf%lf%lf", &s.x, &s.y, &s.z, &s.r);
if(s.r<a.r)swap(a,s);
double ans = 0;
double d = dis(s, a);
if(d>=a.r+s.r+eps)ans=0;
else if (d + a.r <= s.r)ans += calV(a);
else if(d + s.r <= a.r)ans+=calV(s);
else if(fabs(s.r-a.r)<=d+eps&&d<=a.r+s.r+eps)
{
double co = (s.r*s.r + d * d - a.r*a.r) / (2.0*d*s.r);
double h = s.r*(1 - co);
ans += pi*h*h*(s.r-h/3.0);
co = (a.r*a.r + d * d - s.r*s.r) / (2.0*d*a.r);
h = a.r*(1 - co);
ans += pi*h*h*(a.r-h/3.0);
}
printf("%.7lf\n", calV(a)+calV(s)-ans);
return 0;
}