# Program to check two spheres can ever meet by accelerating or not in a 3D space in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose there are two spheres whose radius values are r1 and r2. They are at (x1, y1, z1) and (x2, y2, z2) coordinates. And their acceleration values are given like (ax1, ay1, az1) and (ax2, ay2, az2). We have to check whether these two spheres will ever meet on 3D space if they move with given acceleration or not.

So, if the input is like r1 = 1 r2 = 2 pos1 = (0, 0, 0) acc1 = (100,0,0) pos2 = (4, 0, 0) acc2 = (0,0,0), then the output will be True, because second sphere has no acceleration, so it will not move, but first one will move at x direction so they will collide.

To solve this, we will follow these steps −

• px := pos1[0] - pos2[0]
• py := pos1[1] - pos2[1]
• pz := pos1[2] - pos2[2]
• ax := acc1[0] - acc2[0]
• ay := acc1[1] - acc2[1]
• az := acc1[2] - acc2[2]
• da := ax * ax + ay * ay + az * az
• dp := px * px + py * py + pz * pz
• co := ax * px + ay * py + az * pz
• x := 0.0
• if da is not same as 0, then
• x := - co / da
• x := maximum of x, 0
• dis := square root of (da * x * x + 2 * co * x + dp)
• if dis −= r1 + r2, then
• return True
• otherwise return False

## Example

Let us see the following implementation to get better understanding −

def solve(r1, r2, pos1, acc1, pos2, acc2):
px, py, pz = pos1[0] - pos2[0], pos1[1] - pos2[1], pos1[2] - pos2[2]
ax, ay, az = acc1[0] - acc2[0], acc1[1] - acc2[1], acc1[2] - acc2[2]
da = (ax * ax + ay * ay + az * az)
dp = (px * px + py * py + pz * pz)
co = (ax * px + ay * py + az * pz)

x = 0.0
if da != 0:
x = - co / da
x = max(x, 0)
dis = (da * x * x + 2 * co * x + dp) ** 0.5
if dis <= r1 + r2:
return True
else:
return False

r1 = 1
r2 = 2
pos1 = (0, 0, 0)
acc1 = (100,0,0)
pos2 = (4, 0, 0)
acc2 = (0,0,0)
print(solve(r1, r2, pos1, acc1, pos2, acc2))

## Input

1, 2, (0, 0, 0), (100,0,0), (4, 0, 0), (0,0,0)

## Output

False
Updated on 11-Oct-2021 06:47:52