Finding Pythagorean triples

For this tutorial you may need to read the Wikipedia page about Pythagorean triple (for more information on Pythagorean triple visit http://en.wikipedia.org/wiki/Pythagorean_triple). Pythagorean triples are closely related to the Pythagorean Theorem, which you probably have learned about in high school geometry.

Pythagorean triples represent the three sides of a right triangle, and therefore, obey the Pythagorean Theorem. Let's find the Pythagorean triple that has a components sum of 1000. We will do this using Euclid's formula:

Finding Pythagorean triples

In this example we will see some universal functions in action.

How to do it...

The Euclid's formula defines indices m and n.

  1. Create m and n arrays.

    We will create arrays to hold these indices:

    m = numpy.arange(33)
    n = numpy.arange(33)
  2. Calculate a, b, and c of the Pythagorean triple.

    The second step is to calculate a, b, and c of the Pythagorean triple using Euclid's formula. Use the outer function to get the Cartesian products, difference, and sums we require:

    a = numpy.subtract.outer(m ** 2, n ** 2)
    b = 2 * numpy.multiply.outer(m, n)
    c = numpy.add.outer(m ** 2, n ** 2)
  3. Find the index.

    At this point, we have a number of arrays containing a, b and c values. However, we still need to find the values that conform to the problem's condition. Find the index of those values with the NumPy where function:

    idx =  numpy.where((a + b + c) == 1000)
  4. Check the solution.

    Check the solution with the numpy.testing module:

    numpy.testing.assert_equal(a[idx]**2 + b[idx]**2, c[idx]**2)

The following is the complete code:

import numpy
import numpy.testing

#A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#a ** 2 + b ** 2 = c ** 2
#
#For example, 32 + 42 = 9 + 16 = 25 = 52.
#
#There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#Find the product abc.

#1. Create m and n arrays
m = numpy.arange(33)
n = numpy.arange(33)

#2. Calculate a, b and c
a = numpy.subtract.outer(m ** 2, n ** 2)
b = 2 * numpy.multiply.outer(m, n)
c = numpy.add.outer(m ** 2, n ** 2)

#3. Find the index
idx =  numpy.where((a + b + c) == 1000)

#4. Check solution
numpy.testing.assert_equal(a[idx]**2 + b[idx]**2, c[idx]**2)
print a[idx] * b[idx] * c[idx]

How it works...

Universal functions are not really functions, but objects representing functions. Ufuncs have the outer method, which we saw in action just now. Many of the NumPy standard universal functions are implemented in C, and are, therefore, faster than regular Python code. Ufuncs support element-by-element processing and type casting, which in practice means less loops.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset