Book Image

NumPy Cookbook

Book Image

NumPy Cookbook

Overview of this book

Today's world of science and technology is all about speed and flexibility. When it comes to scientific computing, NumPy is on the top of the list. NumPy will give you both speed and high productivity. "NumPy Cookbook" will teach you all about NumPy, a leading scientific computing library. NumPy replaces a lot of the functionality of Matlab and Mathematica, but in contrast to those products, it is free and open source. "Numpy Cookbook" will teach you to write readable, efficient, and fast code that is as close to the language of Mathematics as much as possible with the cutting edge open source NumPy software library. You will learn about installing and using NumPy and related concepts. At the end of the book, we will explore related scientific computing projects. This book will give you a solid foundation in NumPy arrays and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project through examples. "NumPy Cookbook" will help you to be productive with NumPy and write clean and fast code.
Table of Contents (17 chapters)
NumPy Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Sieving integers with the Sieve of Erasthothenes


The Sieve of Eratosthenes (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) is an algorithm that filters out prime numbers. It iteratively identifies multiples of found primes. This sieve is efficient for primes smaller than 10 million. Let's now try to find the 10001st prime number.

How to do it...

The first mandatory step is to create a list of natural numbers.

  1. Create a list of consecutive integers.

    NumPy has the arange function for that:

    a = numpy.arange(i, i + LIM, 2)
  2. Sieve out multiples of p.

    We are not sure if this is what Eratosthenes wanted us to do, but it works. In the following code, we are passing a NumPy array and getting rid of all the elements that have a zero remainder, when divided by p:

    a = a[a % p != 0]

The following is the entire code for this problem:

import numpy

LIM = 10 ** 6
N = 10 ** 9
P = 10001
primes = []
p = 2

#By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
#What...