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 – detecting collisions: command-line version


This example repeats the previous example using the command-line interface. Create a script in a plain-text editor and enter the following code:

dimension = 20
num_particles = 500
radius = 1.0

rng = RealDistribution('uniform', [0,dimension], seed=1)

x = [rng.get_random_element() for i in range(num_particles)]
y = [rng.get_random_element() for i in range(num_particles)]
z = [rng.get_random_element() for i in range(num_particles)]

import numpy
collisions_1 = numpy.zeros(num_particles, dtype=numpy.bool)

start_time = walltime()
for i in range(num_particles):

    for j in range(0,i):
        r = sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2 + (z[i] - z[j])**2)
        if r < 2*radius:
            collisions_1[i] = True
        
    for j in range(i+1,num_particles):
        r = sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2 + (z[i] - z[j])**2)
        if r < 2*radius:
            collisions_1[i] = True
            
print(walltime(start_time...