50 Examples Documentation Release 1.0

Total Page:16

File Type:pdf, Size:1020Kb

Load more

50 Examples Documentation

Release 1.0

A.M. Kuchling

Apr 13, 2017

Contents

123456789
Introduction

35

Convert Fahrenheit to Celsius Background: Algorithms

9

Background: Measuring Complexity Simulating The Monty Hall Problem Background: Drawing Graphics Simulating Planetary Orbits Problem: Simulating the Game of Life Reference Card: Turtle Graphics

13 17 23 29 35 43 45

10 Indices and tables

  • i
  • ii

50 Examples Documentation, Release 1.0

Release 1.0

Date Apr 13, 2017
Contents:

  • Contents
  • 1

50 Examples Documentation, Release 1.0

  • 2
  • Contents

CHAPTER

1

Introduction

Welcome to “50 Examples for Teaching Python”. My goal was to collect interesting short examples of Python programs, examples that tackle a real-world problem and exercise various features of the Python language. I envision this collection as being useful to teachers of Python who want novel examples that will interest their students, and possibly to teachers of mathematics or science who want to apply Python programming to make their subject more concrete and interactive.

Readers may also enjoy dipping into the book to learn about a particular algorithm or technique, and can use the references to pursue further reading on topics that especially interest them.

Python version

All of the examples in the book were written using Python 3, and tested using Python 3.2.1. You can download a copy of Python 3 from <http://www.python.org/download/>; use the latest version available.

This book is not a Python tutorial and doesn’t try to introduce features of the language, so readers should either be familiar with Python or have a tutorial available. Classes and modules are used right from the beginning, for example; the early programs do not use a subset of the language that’s later expanded by the introduction of more sophisticated features such as classes.

License

The English text of this work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.

This license forbids publishing and selling copies of the book, but you are free to print copies for your own private or educational use. For example, it’s OK to print out a section as a handout for a class, or to include sections in documents that you write and make available under the same Creative Commons license.

3
50 Examples Documentation, Release 1.0

If you wish to sell copies of the book or include partial sections of the text in your own works made available under a different license, please contact the author to request permission.

The software programs are released under the MIT license, and you are free to use or modify them in any way you like, including for commercial purposes or in other documentation projects.

The original source text and example code is available at https://github.com/akuchling/50-examples, and is formatted using the Sphinx documentation tool (http://sphinx.pocoo.org).

Please send questions, suggestions, and comments to the e-mail address below.

A.M. Kuchling

[email protected]

  • 4
  • Chapter 1. Introduction

CHAPTER

2

Convert Fahrenheit to Celsius

We’ll begin with a very simple example to illustrate the format used for each example. Each section will start with a discussion of the problem being solved, giving its requirements and sometimes a brief discussion of its history.

Most of the world uses the Celsius scale to indicate temperatures, but the United States still uses the Fahrenheit scale. We’ll write a little script that takes Fahrenheit temperatures and prints their corresponding values in Celsius. (The author, who’s a Canadian living in the United States, first wrote this script because when listening to weather reports he could never remember if 85 degrees Fahrenheit is pleasantly warm or scorchingly hot.)

Approach

Here we’ll discuss the algorithm or approach taken to solving the problem. The calculation for the temperature conversion is straightforward and references can be found all over the place. Celsius and Fahrenheit have different zero points – 0 degrees Celsius is 32 degrees Fahrenheit – so we need to subtract 32 from the Fahrenheit temperature.

The size of the units are also different. Celsius divides the temperature span between the freezing and boiling points of water into 100 degrees, while Fahrenheit divides this range into 180 degrees, so we need to multiply the value by 5/9 to turn 180 degrees into 100.

Solution

Next we’ll present the complete program listing. The source code for this book also includes test suites for each program, but the test suites won’t be shown in the book.

123456

#!/usr/bin/env python3

import sys def convert_f2c(S):

"""(str): float

5
50 Examples Documentation, Release 1.0

78

Converts a Fahrenheit temperature represented as a string

9

to a Celsius temperature. """

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

fahrenheit = float(S) celsius = (fahrenheit - 32)

return celsius

5 / 9

*

def main():

# If no arguments were given, print a helpful message

if len(sys.argv) == 1:

print('Usage: {} temp1 temp2 ...'.format(sys.argv[0]))

sys.exit(0)

# Loop over the arguments

for arg in sys.argv[1:]: try:

celsius = convert_f2c(arg)

except ValueError:

print("{!r} is not a numeric value".format(arg),

file=sys.stderr)

else:

print('{}\N{DEGREE SIGN}F = {:g}\N{DEGREE SIGN}C'.format(

arg, round(celsius, 0)))

if __name__ == '__main__':

main()

Code Discussion

Here we will dive further into the code, discussing particularly interesting sections of code, programming techniques, or larger issues.

The conversion to Celsius done by the convert_f2c() function is a straightforward calculation. An input string is converted to a floating-point value. If there’s a problem, the resulting ValueError exception is not handled here but instead is left for the caller to catch.

Notice that the main() function tries to print a helpful message when no command-line arguments are provided, and it also catches the ValueError. For pedagogical programs like this, I will try to ensure the error handling is helpful to a user experimenting with the script.

Lessons Learned

Finally, does this program demonstrate any interesting themes about Python, about programming in general, or about its subject matter?

For this celsius example, I’ll discuss Python’s string format() method and the mini-language it uses, since it will be used throughout our example programs.

The strings used with the format() method will contain a replacement field specification inside curly brackets ({ }). It’s possible to leave the specification empty (just {}) but we can also specify the position and type of the argument to use and how the resulting value should be rendered. A few examples:

  • 6
  • Chapter 2. Convert Fahrenheit to Celsius

50 Examples Documentation, Release 1.0

'{!r}'.format(v) '{!s}'.format(v)

# Equivalent to repr(v) # Equivalent to str(v)

# Explicitly give the position of the argument to use for # each field. Results in the string "arg2 arg1"

'{1} {0}'.format('arg1', 'arg2')

We can also specify formatting details such as the number of decimal places, style of numeric display, and left- or right-alignment. This comes within the curly brackets and following a : character.

We can left-align, right-align, or center a string within a desired output width, optionally giving the character to be used for padding:

>>> '{0:<15}'.format('left-justify')

'left-justify

>>> '{0:>15}'.format('right-justify')

right-justify'

>>> '{0: ^15}'.format('centered')

'
'

*

  • '
  • centered
  • '

  • ***
  • ****

We can output a value in binary, octal, decimal, or hexadecimal:

>>> '{0:b}'.format(1972)

'11110110100'

>>> '{0:o}'.format(1972)

'3664'

>>> '{0:d}'.format(1972)

'1972'

>>> '{0:x}'.format(1972)

'7b4'

We can request rounding to a specific number of decimal places, exponential notation, or displaying as a percentage:

>>> '{0:d}'.format(2 32)

**

'4294967296'

>>> '{0:e}'.format(2 32)

**

'4.294967e+09'

>>> '{0:%}'.format( 45 / 70 )

'64.285714%'

>>> '{0:.2%}'.format( 45 / 70 )

'64.29%'

The complete syntax for format strings is documented in the Python Library Reference at <http://docs.python.org/

library/string.html#format-string-syntax>.

References

The references in each section will be to useful web pages, Wikipedia entries, software libraries, and books. Generally each reference is annotated with a short explanation of what’s in it and why it might be of interest, to help you in deciding which references to pursue.

http://books.google.com/books?id=lnmrSAAACAAJ “A Matter of Degrees: What Temperature Reveals About the
Past and Future of Our Species, Planet and Universe”, by Gino Segré, is an entertaining tour through science using the concept of temperature as the connecting thread, including: biological aspects such as the regulation of

  • 2.5. References
  • 7

50 Examples Documentation, Release 1.0

body temperature and the thermophile species that cluster around deep-sea superheated vents; the theoretical arguments underlying global warming; the discovery of the laws of thermodynamics; low-temperature phenomena such as superconductivity and helium’s superfluidity; and the temperature of the cosmic microwave background.

  • 8
  • Chapter 2. Convert Fahrenheit to Celsius

CHAPTER

3

Background: Algorithms

An algorithm specifies a series of steps that perform a particular computation or task. Algorithms were originally born as part of mathematics – the word “algorithm” comes from the Arabic writer Muammad ibn Mu¯sa¯ al-Khwa¯rizm¯ı, – but currently the word is strongly associated with computer science. Throughout this book we’ll examine a number of different algorithms to perform a variety of tasks.

Algorithms resemble recipes. Recipes tell you how to accomplish a task by performing a number of steps. For example, to bake a cake the steps are: preheat the oven; mix flour, sugar, and eggs throughly; pour into a baking pan; and so forth.

However, “algorithm” is a technical term with a more specific meaning than “recipe”, and calling something an algorithm means that the following properties are all true:

• An algorithm is an unambiguous description that makes clear what has to be implemented. In a recipe, a step such as “Bake until done” is ambiguous because it doesn’t explain what “done” means. A more explicit description such as “Bake until the cheese begins to bubble” is better. In a computational algorithm, a step such as “Choose a large number” is vague: what is large? 1 million, 1 billion, or 100? Does the number have to be different each time, or can the same number be used on every run?

• An algorithm expects a defined set of inputs. For example, it might require two numbers where both numbers are greater than zero. Or it might require a word, or a list of zero or more numbers.

• An algorithm produces a defined set of outputs. It might output the larger of the two numbers, an all-uppercase version of a word, or a sorted version of the list of numbers.

• An algorithm is guaranteed to terminate and produce a result, always stopping after a finite time. If an algorithm could potentially run forever, it wouldn’t be very useful because you might never get an answer.

• Most algorithms are guaranteed to produce the correct result. It’s rarely useful if an algorithm returns the largest number 99% of the time, but 1% of the time the algorithm fails and returns the smallest number instead.1

• If an algorithm imposes a requirement on its inputs (called a precondition), that requirement must be met. For

1

There are special situations where algorithms that are sometimes wrong can still be useful. A good example is testing whether a number is prime. There’s an algorithm called the Rabin-Miller test that’s always correct when it reports a number is composite, but has a 25% chance of being wrong when it reports a number is prime. One test therefore isn’t enough to conclude you’ve found a prime, but you can perform repeated tests and reduce the chance of being wrong to as low as you like (but never zero).

9
50 Examples Documentation, Release 1.0

example, a precondition might be that an algorithm will only accept positive numbers as an input. If preconditions aren’t met, then the algorithm is allowed to fail by producing the wrong answer or never terminating.

Studying algorithms is a fundamental part of computer science. There are several different characteristics of an algorithm that are useful to know:

1. Does an algorithm actually exist to perform a given task? 2. If someone proposes an algorithm to solve a task, are we sure that the algorithm works for all possible inputs? 3. How long does the algorithm take to run? How much memory space does it require? 4. Once we know it’s possible to solve a problem with an algorithm, a natural question is whether the algorithm is the best possible one. Can the problem be solved more quickly?

Most of these questions will be discussed for the algorithms covered in this book.

An Example Algorithm

Let’s look at a very simple algorithm called find_max(). Problem: Given a list of positive numbers, return the largest number on the list. Inputs: A list L of positive numbers. This list must contain at least one number. (Asking for the largest number in a list of no numbers is not a meaningful question.)

Outputs: A number n, which will be the largest number of the list. Algorithm:
1. Set max to 0. 2. For each number x in the list L, compare it to max. If x is larger, set max to x. 3. max is now set to the largest number in the list.
An implementation in Python:

def find_max (L):

max = 0

for x in L: if x > max:

max = x

return max

Does this meet the criteria for being an algorithm?
• Is it unambiguous? Yes. Each step of the algorithm consists of primitive operations, and translating each step into Python code is very easy.

• Does it have defined inputs and outputs? Yes.

• Is it guaranteed to terminate? Yes. The list L is of finite length, so after looking at every element of the list the algorithm will stop.

• Does it produce the correct result? Yes. In a formal setting you would provide a careful proof of correctness. In the next section I’ll sketch a proof for an alternative solution to this problem.

  • 10
  • Chapter 3. Background: Algorithms

50 Examples Documentation, Release 1.0

A Recursive Version of find_max()

There can be many different algorithms for solving the same problem. Here’s an alternative algorithm for

find_max():

1. If L is of length 1, return the first item of L. 2. Set v1 to the first item of L. 3. Set v2 to the output of performing find_max() on the rest of L. 4. If v1 is larger than v2, return v1. Otherwise, return v2.
Implementation:

def find_max (L): if len(L) == 1: return L[0]

v1 = L[0] v2 = find_max(L[1:])

if v1 > v2: return v1 else: return v2

Let’s ask our questions again.
• Is it unambiguous? Yes. Each step is simple and easily translated into Python.

• Does it have defined inputs and outputs? Yes.

• Is it guaranteed to terminate? Yes. The algorithm obviously terminates if L is of length 1. If L has more than one element, find_max() is called with a list that’s one element shorter and the result is used in a computation.

Does the nested call to find_max() always terminate? Yes. Each time, find_max() is called with a list that’s shorter by one element, so eventually the list will be of length 1 and the nested calls will end.

Finally, does it produce the correct result? Yes. Here’s a sketch of a proof.2 Consider a list of length 1. In this case the largest number is also the only number on the list. find_max() returns this number, so it’s correct for lists of length 1.

Now consider a longer list of length N+1, where N is some arbitrary length. Let’s assume that we’ve proven that find_max() is correct for all lists of length N. The value of v2 will therefore be the largest value in the rest of the list. There are two cases to worry about.

• Case 1: v1, the first item of the list, is the largest item. In that case, there are no other values in the list greater than v1. We’re assuming find_max() is correct when executed on the rest of the list, so the value it returns will be less than v1. The if v1 > v2 comparison will therefore be true, so the first branch will be taken, returning v1. This is the largest item in the list, so in this case the algorithm is correct.

• Case 2: v1, the first item of the list, is not the largest item. In that case, there is at least one value in the list that’s greater than v1. find_max() is correct for the shortened version of the rest of the list, returning the maximum value it contains, so this value must be greater than v1. The if v1 > v2 comparison will therefore be false, so the else branch will be taken, returning v2, the largest value in the rest of the list. This case assumes that v1 is not the largest value, so v2 is therefore the largest value, and the algorithm is also correct in this case.

With these two cases, we’ve now shown that if find_max() is correct for lists of length N, it’s also correct for lists of length N+1. In the first part of our argument, we’ve shown that find_max() is correct for lists of length 1. Therefore, it’s also correct for lists that are 2 elements long, and 3 elements, and 4, 5, 6, ... up to any number.

2

It’s possible to write formal proofs of correctness for an algorithm, but the resulting proofs are lengthy even for short algorithms such as this one.

  • 3.2. A Recursive Version of find_max()
  • 11

50 Examples Documentation, Release 1.0

This may seem like a trick; we showed that it’s correct for the trivial case of the single-element list, and then showed that it’s correct on a problem of a certain size. Such proofs are called inductive proofs, and they’re a well-known mathematical technique for proving a theorem.

Carrying out an inductive proof of some property requires two steps.
1. First, you show that the property is true for some simple case: an empty list or a list of length 1, an empty set, a single point. Usually this demonstration is very simple; often it’s obviously true that the property is true. This is called the basis case.

2. Next, you assume the property is true for size N and show that it’s true for some larger size such as N+1. This is called the inductive step, and is usually the more difficult one.

Once you have both demonstrations, you’ve proven the property is true for an infinite number of values of N; correctness for N=1 implies that the N=2 case is also correct, which in turn implies correctness for N=3, 4, 5, and every other positive integer. Not every theorem can be put into a form where an inductive proof can be used.

References

XXX something on induction

  • 12
  • Chapter 3. Background: Algorithms

CHAPTER

4

Background: Measuring Complexity

It’s obviously most important that an algorithm solves a given problem correctly. How much time an algorithm will take to solve a problem is only slightly less important. All algorithms must terminate eventually, because they wouldn’t be algorithms if they didn’t, but they might run for billions of years before terminating. In order to compare algorithms, we need a way to measure the time required by an algorithm.

Recommended publications
  • Life[M List?Matrixq, {G1 Integer?Nonnegative, G2 Integer?Nonnegative}] := Cellularautomaton[ { 224, {2, {{2, 2, 2}, {2, 1, 2}, {

    Life[M List?Matrixq, {G1 Integer?Nonnegative, G2 Integer?Nonnegative}] := Cellularautomaton[ { 224, {2, {{2, 2, 2}, {2, 1, 2}, {

    Life The best-known two-dimensional cellular automaton, invented by John H. Conway and popularized in Martin Gardner's Scientific American column starting in October 1970. Life, sometimes also called "the game of life," was originally played (i.e., successive generations were produced) by hand with counters, but implementation on a computer greatly increased the ease of exploring patterns. The life cellular automaton is run by placing a number of filled cells on a two-dimensional grid. Each generation then switches cells on or off depending on the state of the cells that surround it. The rules are defined as follows. All eight of the cells surrounding the current one are checked to see if they are on or not. Any cells that are on are counted, and this count is then used to determine what will happen to the current cell. 1. Death: if the count is less than 2 or greater than 3, the current cell is switched off. 2. Survival: if (a) the count is exactly 2, or (b) the count is exactly 3 and the current cell is on, the current cell is left unchanged. 3. Birth: if the current cell is off and the count is exactly 3, the current cell is switched on. The game of life is a totalistic cellular automaton, and can be implemented as follows using the built-in command CellularAutomaton, where the initial conditions are specified as a binary matrix and the results for generations through are returned. (Here, corresponds to the initial pattern.) Life[m_List?MatrixQ, {g1_Integer?NonNegative, g2_Integer?NonNegative}] := CellularAutomaton[ { 224, {2, {{2, 2, 2}, {2, 1, 2}, {2, 2, 2}}}, {1, 1} }, {m, 0}, g2, { {g1, g2}, Automatic }] /; g2>=g1 Weisstein gives an extensive alphabetical tabulation of life forms and terms.
  • Martin Gardner Papers SC0647

    Martin Gardner Papers SC0647

    http://oac.cdlib.org/findaid/ark:/13030/kt6s20356s No online items Guide to the Martin Gardner Papers SC0647 Daniel Hartwig & Jenny Johnson Department of Special Collections and University Archives October 2008 Green Library 557 Escondido Mall Stanford 94305-6064 [email protected] URL: http://library.stanford.edu/spc Note This encoded finding aid is compliant with Stanford EAD Best Practice Guidelines, Version 1.0. Guide to the Martin Gardner SC064712473 1 Papers SC0647 Language of Material: English Contributing Institution: Department of Special Collections and University Archives Title: Martin Gardner papers Creator: Gardner, Martin Identifier/Call Number: SC0647 Identifier/Call Number: 12473 Physical Description: 63.5 Linear Feet Date (inclusive): 1957-1997 Abstract: These papers pertain to his interest in mathematics and consist of files relating to his SCIENTIFIC AMERICAN mathematical games column (1957-1986) and subject files on recreational mathematics. Papers include correspondence, notes, clippings, and articles, with some examples of puzzle toys. Correspondents include Dmitri A. Borgmann, John H. Conway, H. S. M Coxeter, Persi Diaconis, Solomon W Golomb, Richard K.Guy, David A. Klarner, Donald Ervin Knuth, Harry Lindgren, Doris Schattschneider, Jerry Slocum, Charles W.Trigg, Stanislaw M. Ulam, and Samuel Yates. Immediate Source of Acquisition note Gift of Martin Gardner, 2002. Information about Access This collection is open for research. Ownership & Copyright All requests to reproduce, publish, quote from, or otherwise use collection materials must be submitted in writing to the Head of Special Collections and University Archives, Stanford University Libraries, Stanford, California 94304-6064. Consent is given on behalf of Special Collections as the owner of the physical items and is not intended to include or imply permission from the copyright owner.
  • The Game of Life Trad

    The Game of Life Trad

    The Game of Life -“If I sometimes smoked one way [...] sometimes another, sometimes not at all, varied the way I dressed, was nervous, serene, ambitious, lazy, lecherous, gluttonous, ascetic – where would my `self ́ be? What would I achieve? It’s the way a man chooses to limit himself that determines his character. A man without habits, consistency, redundancy – and hence boredom – is not human. He’s insane.” -“And accepting these self- defeating limitations is mental health?” I said. Luke Rhinehart, The Dice Man, Harper-Collins, 1999, pp. 65-66. Gaël Charbau: A “retrospective”... there’s a word I never thought I’d use about your work at such an early stage. Maybe “introspective” is a better description of this short exploration of your work. The larousse dictionary defines “introspection” as: “methodical observation of personal states of consciousness and inner life.” What are your thoughts? Gilles Barbier: Some of the work is twenty-five years old. That’s half my life. The direction of my work, however, has been based on drift and retrospective narratives have difficulty mapping out this fluid form which has no backbone. It isn’t easy to recount twenty-five years of drifting on an artificial lake without currents, winds, wrecks and islands, without making what is a maiden voyage appear disordered and agitated. This is my relationship to art. It is easier to talk about the holes, the bananas, the leaks, the insatiable hunger, the engines cutting out, the desire for treasure, and the great absentee, time, which is manifest only through its effects. GC: I wanted to ask you about the holes theme.
  • Tony Smith Complex Systems Analyst Meme Media Ts@Meme.Com.Au

    Tony Smith Complex Systems Analyst Meme Media [email protected]

    Golly: how an open source project took over the study of cellular automata. Tony Smith Complex Systems Analyst Meme Media [email protected] Open Source Developers' Conference Thursday, 25 November 2010, 14:30 Melbourne, Australia 1 A long prehistory The basic idea: A grid of cells in which the next state of each cell is determined by the previous state of the cells in its immediate neighbourhood through some rule. John Horton Conway discovered an interesting rule whereby a live cell would stay live if it had two or three live neighbours of eight and an empty cell would turn live if it had exactly three, calling it the Game of Life and having it described in Martin Gardner’s Mathematical Games column in Scientific American in October 1970. In the article Conway offered a $50 prize to the first person who, before the end of 1970, could prove or disprove his initial conjecture that no pattern can grow indefinitely. One way to disprove it would be to discover patterns that keep adding counters to the field: a gun, which would be a configuration that repeatedly shoots out moving objects such as the glider. The prize was won that November by a team from the Massachusetts Institute of Technology, led by Bill Gosper. 2 Cellular Automata needed computers • Ed Fredkin’s trivial solution to reproducing patterns in cellular automata reported in Scientific American in 1983. • Wolfram, Stephen, “Universality and Complexity in Cellular Automata,” Physica D, 1984, 10 (January) 1-35. Classes 1-4. • Poundstone, William, The Recursive Universe: Cosmic Complexity and the Limits of Scientific Knowledge, Chicago: Contemporary Books, 1985.
  • Conway's Game of Life Accelerated with Opencl

    Conway's Game of Life Accelerated with Opencl

    Conway's Game of Life accelerated with OpenCL Thomas Rumpf Friedrich-Schiller-University Jena, Germany Department of Mathematics and Computer Science [email protected] Abstract. We introduce a massively data-parallel implementation of John Conway's cellular automaton Game of Life in-silico which provides the user with a high flexibility to modify initial settings and progression rules. Written in C/C++ and employing the open programming inter- face OpenCL our program utilizes the parallel computing architecture of modern graphics cards leading to a significant speed-up in estimat- ing artificial life-form generations in comparison to ordinary CPU-based implementations. Custom input files for specification of initial configu- rations as well as a variety of features to control the course of the game on the fly contribute to improve the productivity in conducting experi- mental studies using our cellular automaton framework. Key words: Game of Life, OpenCL, OpenGL, parallel computing, GPGPU 1 Introduction John Conway designed the cellular automaton Game of Life in 1970 to prove that it is possible to build a simple yet powerful machine which can simulate the basic concepts of life. The outcome of his automaton had to be unpredictable meeting three desiderata: firstly there should be no initial pattern for which there is a simple proof that the population can grow without limit, secondly initial patterns that apparently do grow without limit and thirdly initial patterns fading away, settling into a stable configuration or entering an oscillating phase [2]. He achieved these goals employing a simple two-dimensional board of equally shaped cells which had only two states { dead or alive.
  • Life Algorithms

    Life Algorithms

    Life Algorithms Tomas Rokicki June 28, 2018 Abstract We describe some ideas on how to implement Conway’s Game of Life. 1 Introduction Conway’s Game of Life serves as the “Hello World” of recreational computing. Many of us who cut our teeth on minicomputers or microcomputers will remember writing our own implementations, and then struggling to make them faster [5]. In this paper we briefly describe some of the more interesting ways to implement Life, without taking the fun out of getting all the details of implementation exactly correct. We will focus on calculating subsequent generations from current generations, ignoring the impact on other operations such as loading and saving patterns, setting and clearing cells, calculating the current population of the universe, and displaying the pattern. We will also ignore the impact of the borders (if any) of the universe. In a real Life program, all of these are important aspects that should be considered before adopting a too-complex algorithm. All the code for this paper is available at https://github.com/rokicki/lifealg along with more in- formation and performance comparisons. We include the algorithms in the Golly program as well as high-performance algorithms created by Adam Goucher as part of his lifelib project. 2 Elementary Approaches: Arrays 2.1 Basic Algorithm The most fundamental implementation of the Game of Life uses two two-dimensional arrays repre- senting the current universe and the universe in the next generation. Computing the next generation array from the current generation array involves iterating over all the cell positions, calculating the number of live neighbors to that cell from the current generation array, and then determining if the next generation cell is alive or dead based on this neighbor count and the life status of the current generation cell.
  • Large Scale Cellular Automata on Fpgas: a New Generic Architecture and a Framework

    Large Scale Cellular Automata on Fpgas: a New Generic Architecture and a Framework

    Large Scale Cellular Automata on FPGAs: A New Generic Architecture and a Framework NIKOLAOS KYPARISSAS∗ and APOSTOLOS DOLLAS, Technical University of Crete, Greece Cellular Automata (CA) are discrete mathematical models discovered in the 1940s by John von Neumann and Stanislaw Ulam, and used extensively in many scientific disciplines ever since. The present work evolved from a Field Programmable Gate Array (FPGA)-based design to simulate urban growth into a generic architecture which is automatically generated by a framework to efficiently compute complex cellular automata with large 29 × 29 neighborhoods in Cartesian or toroidal grids, with 16- or 256-states per cell. The new architecture and the framework are presented in detail, including results in terms of modeling capabilities and performance. Large neighborhoods greatly enhance CA modeling capabilities, such as the implementation of anisotropic rules. Performance-wise, the proposed architecture runs on a medium-size FPGA up to 51 times faster vs. a CPU running highly optimized C code. Compared to GPUs the speedup is harder to quantify because CA results have been reported on GPU implementations with neighborhoods up to 11 × 11, in which case FPGA performance is roughly on par with GPU; however, based on published GPU trends, for 29 × 29 neighborhoods the proposed architecture is expected to have better performance vs. a GPU, at one-tenth the energy requirements. The architecture and sample designs are open source available under the creative commons license. CCS Concepts: • Computer systems organization ! Real-time system architecture; Special purpose systems; • Computing methodologies ! Real-time simulation; • Hardware ! Reconfigurable logic applications; Hardware accelerators. Additional Key Words and Phrases: cellular automata, generic architecture, framework, FPGA accelerator ACM Reference Format: Nikolaos Kyparissas and Apostolos Dollas.
  • Solvers to Search for Patterns

    Solvers to Search for Patterns

    Searching for patterns in Conway’s Game of Life Town Cape of Johan Bontes Minor dissertation presented in partial fulfilment of the requirements for the degree of Master of Science in the department of Computer Science UniversityUniversity of Cape Town Supervisor: Prof. James Gain 18 September 2019 The copyright of this thesis vests inTown the author. No quotation from it or information derived from it is to be published without full acknowledgement of the source. The thesis is to be used for private study or non- commercial research purposes Capeonly. of Published by the University of Cape Town (UCT) in terms of the non-exclusive license granted to UCT by the author. University 2 Abstract Conway’s Game of Life (Life) is a simple cellular automaton, discovered by John Conway in 1970, that exhibits complex emergent behavior. Life-enthusiasts have been looking for building blocks with specific properties (patterns) to answer unsolved problems in Life for the past five decades. Finding patterns in Life is difficult due to the large search space. Current search algorithms use an explorative approach based on the rules of the game, but this can only sample a small fraction of the search space. More recently, people have used Sat solvers to search for patterns. These solvers are not specifically tuned to this problem and thus waste a lot of time processing Life’s rules in an engine that does not understand them. We propose a novel Sat-based approach that replaces the binary tree used by traditional Sat solvers with a grid-based approach, complemented by an injection of Game of Life specific knowledge.