Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:
            collisions_4[i] = True

    for j in range(i+1,num_particles):
        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]) \
 ...