O'Reilly logo

Sage Beginner's Guide by Craig Finch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Time for action - using NumPy

Enter the following code in a new cell in the worksheet to define the spheres using NumPy:

import numpy
dimension = 20
num_particles = 500
radius = 1.0
rng = numpy.random.mtrand.RandomState(seed=[1])
x_np = rng.uniform(0, dimension, num_particles)
y_np = rng.uniform(0, dimension, num_particles)
z_np = rng.uniform(0, dimension, num_particles)

Now, enter the following code in another cell to detect collisions:

 %time collisions_4 = numpy.zeros(num_particles, dtype=numpy.bool) r_min = numpy.float64(4*radius**2) for i in range(num_particles): for j in range(0,i): r_squared = (x_np[i] - x_np[j])*(x_np[i] - x_np[j]) \ + (y_np[i] - y_np[j])*(y_np[i] - y_np[j]) \ + (z_np[i] - z_np[j])*(z_np[i] - z_np[j]) if r_squared < r_min: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required