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 – faster collision detection


In this example, we are going to apply a couple of simple tricks and see how they impact the runtime. Assuming you've already defined the spheres in the previous example, you can enter and run the following code in a worksheet cell:

%time
import numpy
collisions_2 = numpy.zeros(num_particles, dtype=numpy.bool)

r_min = 4*radius**2

for i in range(num_particles):
    for j in range(0,i):
        r_squared = (x[i] - x[j])**2 + (y[i] - y[j])**2 + (z[i] - z[j])**2
        if r_squared < r_min:
            collisions_2[i] = True

    for j in range(i+1,num_particles):
        r_squared = (x[i] - x[j])**2 + (y[i] - y[j])**2 + (z[i] - z[j])**2
        if r_squared < r_min:
            collisions_2[i] = True

The code will print the runtime:

It's about twice as fast! Not bad for two minor changes. Now, try this:

%time
import numpy
collisions_3 = numpy.zeros(num_particles, dtype=numpy.bool)

r_min = 4*radius**2

for i in range(num_particles):
    for...