More ‘Spirograph (®) plots using ‘matplotlib’

‘Spirograph’ includes toothed rings which can be used with small disks to draw Spirograph patterns inside the ring. The small toothed rolls around the inside of the fixed ring, producing the typical Spirograph spirals.

The diagram above shows how this works. The small circle rolls around inside the larger circle (which represents the inside of the ring). If there is no slippage, the small circle rotates in the opposite direction to its movement around the larger circle.

I modified my Python program to simulate this situation. As before, the rate of rotation of the smaller circle can be controlled by varying the ‘mult2’ variable in the program. To start with I used a small value for the variable as shown below.

The diagram has five ‘lobes’ and an empty patch in the middle. The curve can never go through the centre. If the ratio of the sizes of the circles is less than one half, then smaller circle is not big enough to reach the centre of the larger circle. If the ratio of the sizes of the circles is greater than one half, then the point on the circumference of the smaller circle that is drawing the curve (point D on the diagram above) never falls on the centre of the larger circle. If the ratio of sizes is exactly one half, all the loops will pass through the centre of the larger circle.

As the multiplier ‘mult2’ is increased, the curve comes to resemble the circular shape of a typical Spirograph. I think that it looks a bit like a torus or a donut.

I’m not going to try to emulate the behaviour of the non-circular Spirograph components. In fact, I have only emulated the circular ones, but not completely. I’ve only plotted the curves that would result if the point P (the pen) corresponded to the point D (on the smaller circle) in the diagram above.

Here’s one final plot, where the ratio of the smaller circle to the larger circle is exactly one half. The program draws a pleasant chrysanthemum or dahlia shape.

Finally, here’s the Python program that I used to draw these diagrams. To get the different figures, I’ve changed the multipliers, mainly ‘mult2’. I’ve also changed the sizes of the circles (variables ‘large’ and ‘small’) to get some of them.


import numpy as np
import matplotlib.pyplot as plt

# Dimensions of two circles
r1 = 100
r2 = 50
# c0 = [0,0]
# c1 = [1,0]

# Multipliers
mult = 10   # Used to generate the number of points plotted.
mult2 = 25  # Controls speed of rotation of the smaller circle, relative to the first.

ax = plt.subplot()
ax.set_aspect( 1 )

# Parametric array for the larger circle
t1 = np.linspace(-2 * np.pi, 2 * np.pi, mult * 360)
# Parametric array for the smaller circle
t2 = t1 * mult2

# Calculation of X/y cordinates using the parametric arrays.
# x0 and y0 are the coordinates of the tangential point, B.
x0 = r1 * np.cos(t1)
y0 = r1 * np.sin(t1)
# plt.plot(x0, y0, label=("Large circle"), color = 'r', linewidth = 2, linestyle = '--')
# x1 and y1 are the cordinates of the centre of the small circle, C.
x1 = (r1 - r2) * np.cos(t1)
y1 = (r1 - r2) * np.sin(t1)
# x1a and y1a are the coordinates of D relative to C.
x1a = r2 * np.cos(t2)
y1a = r2 * np.sin(t2)
# plt.plot(x1a, y1a, label=("Small circle"), c = 'r', linewidth = 2, linestyle = '--')
# x2 and y2 are the coordinates of the desired point on the curve, D.
plt.plot(x0[0],y0[0], color='r')
# The small circle rolls in the opposite direction if it is inside
x2 = r2 * np.cos(-t2)
y2 = r2 * np.sin(-t2)

# Plot the Curve
# plt.plot(x1 - 1.5 * x2, y1 - 1.5 * y2)
plt.plot(x1 + x2, y1 + y2, label=("'Spirograph' curve"), c = 'b', linewidth = 1)

plt.title("Inside, mult = {}, mult2 = {} ".format(mult, mult2))
plt.legend(loc="upper right")
plt.show()

Drawing ‘Spirograph'(®)-like Curves with matplotlib

‘Spirograph’® is a set of devices which can be used to draw some interesting looping curves. It consists of various toothed wheels and other toothed shapes with small holes them. A wheel or other shape is chosen, and fixed to the drawing surface. A second wheel is placed so that its teeth interlock with the teeth on the second wheel and a pen is inserted into a hole in the second wheel. The pen is moved to keep the two gear wheels enmeshed at all times. As a result the pen traces out a curve.

This can, of course, be plotted mathematically, using a tool like ‘matplotlib’. The above diagram shows how the Spirograph system works. The circle representing the first wheel is centred on point A and is fixed. The other circle is centred on point C, rolls around the first circle, and is always in contact with the first circle at point B. The point P is a point inside the smaller circle, and the line CD is the radius which passes through point B.

It is easy to see that the centre of the smaller circle (C) travels in a larger circle around the static circle. This larger circle (not drawn) has a radius is equal to the sum of the radii of the two circles. This radius corresponds to the line AC. As C travels around the circle, the smaller circle, CD, rotates. Meanwhile, the point P on CD traces out the curve we are interested in.

In the ‘Spirograph’ case, the two circles are linked by the teeth on the gears wheels. This connection ensures that the smaller circle rotates at a fixed speed. The Wikipedia page on the ‘Spirograph’ system mentions that the teeth prevent any slipping.

In the program generated case, smaller wheel can be programmed to rotate at any rate that is desired, with ‘slippage’. It can, for example, be programmed to move around the large circle without rotating at all. The next image shows what happens then. [Note: For simplicity, the point P is assumed to be located on the circumference of the small circle.]

The plot shows large fixed circle drawn with a dashed line. The small circle is not visible because it is actually a single point. The ‘Spirograph’ curve is just a larger circle offset from the centre of the large circle.

If the small circle rolls around the larger circle without slipping, then the ratio of small circle to the large should be exactly in the ratio of the radius of the small circle to the radius of the large circle. So in this next image, the size of the small circle is 75, and the size of the large circle is 100. The smaller circle rotates 100/75 (4/3) times every time it goes around the large circle.

I’m going to finish up with a couple more images that look more like a standard ‘Spirograph’. The point P is still on the circumference of the smaller circle, but this makes little difference to the plots.

This show a typical curve that a ‘Spirograph’ would plot. The ‘mult2’ parameter controls how many lobes the figure has. In this case, with a value of 25, there should be 24 lobes.

Finally, this image, with a mult2 value of 67 will have 66 lobes. When a Spirograph Wheel rotates around a fixed wheel, the pattern typically shows a rosette of loops, with a hole in the middle where the fixed wheel is located. I’m going to experiment with a moving wheel inside and if it is interesting I might do another post on the topic of ‘Spirographs’.

?Below I have pasted the program that I used to draw these images. Feel free to take it and alter it as much as you like.

import numpy as np
import matplotlib.pyplot as plt

# Dimensions of two circles
r1 = 100
r2 = 75
# c0 = [0,0]
# c1 = [1,0]

# Multipliers
mult = 10
mult2 = 67  # was 11

ax = plt.subplot()
ax.set_aspect( 1 )

# Parametric array for the larger circle
t1 = np.linspace(-2 * np.pi, 2 * np.pi, mult * 360)
# Parametric array for the smaller circle
t2 = t1 * mult2

# Calculation of X/y coordinates using the parametric arrays.
# x0 and y0 are the coordinates of the tangential point, B.
x0 = r1 * np.cos(t1)
y0 = r1 * np.sin(t1)
# plt.plot(x0, y0, label=("Large circle"), color = 'g', linewidth = 1, linestyle = '--')
# x1 and y1 are the cordinates of the centre of the small circle, C.
x1 = (r1 + r2) * np.cos(t1)
y1 = (r1 + r2) * np.sin(t1)
# x1a and y1a are the coordinates of D relative to C.
x1a = r2 * np.cos(t2)
y1a = r2 * np.sin(t2)
# plt.plot(x1a, y1a, label=("Small circle"), c = 'r', linewidth = 3, linestyle = '--')
# x2 and y2 are the coordinates of the desired point on the curve, D.

x2 = r2 * np.cos(t2)
y2 = r2 * np.sin(t2)

# Plot the Curve
# plt.plot(x1 - 1.5 * x2, y1 - 1.5 * y2)
plt.plot(x1 + x2, y1 + y2, label=("'Spirograph' curve"), c = 'b', linewidth = 1)

plt.title("mult = {}, mult2 = {} ".format(mult, mult2))
plt.legend(loc="upper right")
plt.show()

Plotting with ‘matplotlib’

What is ‘matplotlib’? It’s a Python package which can be used to plot everything from a simple parabola or sine wave right up to complex statistical data. Of course, I use it just to print interesting curves, like the one above. I’ll discuss the program I wrote below.

Since it is a Python package it helps if you know how to write Python programs, but I don’t dive too deep into Python. Anyway, the above curves were printed by a program that is only eleven lines long!

At the top of the Python code, we need to tell it to use ‘matplotlib’ and I’ve included a line to tell the code that we need to use the ‘numpy’ maths package. Here’s the first bit of the program:

import matplotlib.pyplot as plt  # This is the plotting library
import numpy as np               # A common Python package

Plotting something involves matching one set of data against another. Commonly these sets of data are named ‘x’ and ‘y’, but they can have any names that the plotter desires. The relevant code in this program is as follows:

max_range = 1000
x = np.linspace(-2*np.pi, 2*np.pi, max_range)
y = np.sin(x)

The line that starts ‘x =’ uses the numpy ‘linspace’ routine to generate a numpy array of one thousand (max_range) elements evenly spaced between -2 time pi and 2 times pi. The line that starts ‘y =’ then creates another numpy array, taking the individual elements of the array x, applying the numpy sine function and appending the result to the end of the array y.

In the earliest version of this program, I created the two numpy arrays by means of a loop, but by creating numpy arrays using this method, I can do it in two lines. Like all good ideas I got it from someone else’s program on the Internet. There is only one program, the old joke goes, and that is the “Hello World!” program, and all other programs are descendants of that single archetype.

OK, so, I created two more arrays using the same technique, and here are the two lines of code:

z = np.sin(2*x)
zz = np.sin(4*x)

So, I could have drawn three plots, one for each array, but that wouldn’t have been that interesting, so I decide to plot the sum of all three arrays (against the x array), and also the product of all three arrays (again, against the x array). Numpy arrays make this easy.

# y = np.sin(x) * np.sin(2*x) * np.sin(4*x)
plt.plot(x, y * z * zz, label='product')
# y = np.sin(x) + np.sin(2*x) + np.sin(4*x)
plt.plot(x, y + z + zz, label='sum')

The ‘plot’ statements each draw a line in the final figure, and generate a label for the line. The comments describe the curve in an x/y format, in a simple mathematical style .

The final couple of lines (see below) are needed to show the labels and the complete figure. Below is the whole Python program, comments and all.

import matplotlib.pyplot as plt
import numpy as np

# Basic Figures
# sine wave
max_range = 1000
x = np.linspace(-2*np.pi, 2*np.pi, max_range)
y = np.sin(x)

# sine wave, freq * 2
# x = np.linspace(-2*np.pi, 2*np.pi, max_range)
z = np.sin(2*x)
zz = np.sin(4*x)

# y = np.sin(x) * np.sin(2*x) * np.sin(4*x)
plt.plot(x, y * z * zz, label='product')
# y = np.sin(x) + np.sin(2*x) + np.sin(4*x)
plt.plot(x, y + z + zz, label='sum')

plt.legend()
plt.show()

To close the post, I’m going present a more complex example. This one combines the plots described above, with a separate subplot of the three waves that were used to create the first subplot. At the very end is the source code.

import matplotlib.pyplot as plt
import numpy as np

# Basic Figures
# sine wave
max_range = 1000

fig, (ax1, ax2) = plt.subplots(2, 1)

# The x array runs from -2*pi to +2*pi
x = np.linspace(-2*np.pi, 2*np.pi, max_range)

# One component of the final plot
y = np.sin(x)

# sine wave, freq * 2
z = np.sin(2*x)
# Freq * 4
zz = np.sin(4*x)import matplotlib.pyplot as plt
import numpy as np

# Basic Figures
# sine wave
max_range = 1000

fig, (ax1, ax2) = plt.subplots(2, 1)

# The x array runs from -2*pi to +2*pi
x = np.linspace(-2*np.pi, 2*np.pi, max_range)

# One component of the final plot
y = np.sin(x)

# sine wave, freq * 2
z = np.sin(2*x)
# Freq * 4
zz = np.sin(4*x)
ax1.plot(x, y, label='sin(x)')
ax1.plot(x, z, label='sin(2*x)')
ax1.plot(x, zz, label='sin(4*x)')

legend1 = ax1.legend()

# y = sin(x) * sin(2x) * sin(4x)
ax2.plot(x, y * z * zz, label='product')
# y = sin(x) + sin(2x) + sin(4x)
ax2.plot(x, y + z + zz, label='sum')

legend2 = ax2.legend()

plt.show()
ax1.plot(x, y, label='sin(x)')
ax1.plot(x, z, label='sin(2*x)')
ax1.plot(x, zz, label='sin(4*x)')

legend1 = ax1.legend()

# y = sin(x) * sin(2x) * sin(4x)
ax2.plot(x, y * z * zz, label='product')
# y = sin(x) + sin(2x) + sin(4x)
ax2.plot(x, y + z + zz, label='sum')

legend2 = ax2.legend()

plt.show()

A Simple KmPlot Example

A simple sine wave is not that interesting. However adding sine waves together can produce something more aesthetically satisfying. I could, for example, add another sine wave with a higher frequency to the above simple sine wave, as shown below.

The above diagram shows the result of adding a sine wave of three times the original frequency to the first wave. Below I show the result of adding a third sine wave of five times the original fequency to the first.

A pattern is beginning to emerge from this process. I’ll add a few more terms to the summation.

This shows the sum of the terms up to the the term for the sine wave which is 13 times the original frequency. Those who have done some maths probably recognise that this is tending towards a square wave. Here’s a link to a MatLab version of what I’ve done here.

Here’s a depiction of all the individual waves that have been added together, plus the final result.

Here’s an image of just a few of the waves. It’s probably more aesthetic than the full set!

A couple of times when I was creating the above series of plots, I made mistakes, and ended up with some more interesting graphs, but I discarded those ‘mistakes’ and stuck closely to my original idea, which was to show how simply adding a few sine waves together could result in an approximate square wave.

In fact the Fourier series for a square wave can be expressed as an infinite sum of sine waves, as shown here. A fairly complex mathematical fact can be approximated by a few simple plots.

Now I’m going to go back to the ‘mistakes’ that I made and rejected earlier when developing and writing this post.

What’s the answer?

The Maths is out There

Last year I posted an article which discussed some simple arithmetic and algebraic expressionss that people are posting on the Internet. I mentioned in that post that the questions are not posted to be answered. They are posted to incite discussion. Since then, there has been an upsurge of such postings, and I am going to address this topic further and expand on it.

Most people have left school with the impression that there is only one way to solve an arithmetic or algebraic question, and there is only ever one correct answer.

This is true, in a way. The rules of maths are rigid. However, when we write a problem down on paper, we write down a representation of the maths, in symbols. In the simplest case, we write down the symbol for a number, eg the symbol ‘7’. However in Ancient Rome, a mathematician would have written the symbols ‘VII’ to represent the same number. Even when we say the word ‘seven’, the word is only a name for the number.

Of course, our minds cut out all these distractions, and we, inaccurately, conflate the number and the symbol or name for the number. “This is the number seven,” we say, pointing to the symbol, but it isn’t.

When we add mathematical operations into the mix, things get more complicated of course. We write “7 + 3”, and think “Seven plus three”, mentally come up with the sum, the number 10, and think everything is fine.

But what if we were from a culture that reads and writes from right to left? We might possibly think “Three plus seven”, and would come up with the sum, the number 10.

However the language that we would use is unlikely to be the same as the one that I am using here, and the symbols would be different. Nevertheless, in some eldritch way, the maths is identical.

In this rather long preamble I have suggested that mathematics, specifically arithmetic and algebra, is independent of the symbols on the paper, and, probably, independent of the way our brains think of maths.

The Need for an ‘Order of Operations’

From now on I’m going to assume that that we are not from a culture that reads and writes from right to left, but the following reasoning can be expressed in a similar way for those who do write that manner.

Now, if I multiply two numbers I get a third number. I’m not too concerned about what multiplication actually is, but essentially I am taking two (or more) number, doing something with them and ending up with a single, different number. I can communicate this idea to someone else by writing down the two numbers with a multiplication symbol between them. I might then write a ‘=’ symbol next, and then the result.

5 x 4 = 20

A string of multiplications is easy:

5 x 4 x 2 = 40

Similarly with addition:

5 + 4 + 2 = 11

So far so good. Note that it makes no difference which order we perform the multiplications or additions. If we decide to start with the ‘2’, rather than the ‘5’, we get the same answer at the end. ‘5 x 4′ gives us ’20’ and so does ‘4 x 5’.

Problems arise when we introduce division and subtraction into the mix. Firstly, you can’t reverse the order in which you perform a subtraction or division:

5 - 4 = 1, but 4 - 5 = -1
Worse, 5 - 4 - 2 = 1 - 2 = -1, but 5 - 4 - 2 = 5 - 2 = 3

Even worse things happen when you mix addition and subtraction with multiplication and division. It’s important to note that the order that we should perform operations on numbers is not an essential part of arithmetic and algebra, but is related to the way we portray numbers and operations on paper.

So, mathematicians introduced the concept of the order of operations. This simply means that there are conventions for writing down arithmetical and other mathematical processes, in a way that someone else can take the expression, evaluate it and reach the same result as the originator of the expression.

There are ways of writing mathematical expressions which do not need an order of operations (or brackets, see later), indicating that the issues are not something within mathematics itself, but I’ll leave that for another time.

There are two ways of of writing an arithmetic or algebraic expressions in a way that can be communicated to someone else. Firstly, an order of operations rule can be applied to writing such expressions. Then expressions such as

1 - 21 / 7 + 4 * 2 =  6

can be written and understood unequivocally. The order of operation rules that are most often used are usually referred by the mnemonic PEMDAS or BODMAS.

Secondly, brackets can be used to specify the order that operations should be performed. The previous example could have been written as

(1 - (21/7)) + (4 * 2) = 6

You can always add brackets to an expression, even if they are not essential, as above.

So, if we agree to use PEMDAS, we can pass equations to and fro with a good chance of agreeing on the results, but there are some edge cases.

Is PEMDAS enough?

Some people write things like

2 / 3(5 -2)

I think that this is badly formed, and one should not write ‘…3(5…’, but people do it all the time. That said, there is an implied multiplication symbol between the ‘3’ and ‘(‘, so the same thing, with the implicit multiplication made explicit is

2 / 3 * (5 - 2)

Now there are two schools of thought on how this expression should be processed. The first group say that there is nothing special about the multiplication sign and the rules should be applied as usual. That is, from left to right as each symbol is reached.

2 /  3 * (5 - 2) = 2 / 3 * 3 = 2

The other group say that because the multiplication sign is implicit, the multiplication between the ‘3’ and the bracketed item should be processed as soon as the bracket is evaluated, before the usual left to right processing. In other words

2 / 3 * (5 - 2) = 2 / 3 * 3 = 2 / 9 = 2/9

The two schools of thought result in different answers, so which is correct? The answer is either or both. It depends on what the writer intended, and he/she could have used a set of brackets and made certain that the idea was communicated properly.

Why is it such a big thing on the Internet?

People like to cause arguments! So they post ‘quizzes’ on the Internet which are ambiguous, and then sit back and watch the fireworks. Other people read the posts and provide answers which are informed or not informed as the case may be.

Then those who think that they know, mock those who they think are wrong. Neither side acknowledge the fact that it is a communications problem. There are those who try to point this out, but they are often ignored.

Those who know of BODMAS/PEMDAS are usually adamant that they are right because it’s maths and they were taught it, right? Those who don’t are ridiculed. The BODMAS/PEMDAS believers are certain that they are correct because, it’s maths, isn’t it, and maths is never wrong. They lose track of the fact that PEMDAS/BODMAS is just a convention , and other conventions, such ‘strict left to right’ or SADMEP/SAMDOB (the reverse of BODMAS/PEMDAS) could be used. Providing both parties agree on a convention, they can communicate mathematical (well, arithmetical or algebraic) ideas successfully to each other.

Those who have been taught about implied multiplication by juxtaposition dispute the answer with those who haven’t heard of it, but really, the answer to the poser is irrelevant. The reason for that people post these dubious and intriguing equations is not to seek a value for equation. It’s not to find ‘the answer’. It’s usually to stir discussion, and the rowdier the discussion is, the better from the poster’s point of view.

A Long Long Way to Go

River valley (Blender)
My first attempt at a landscape with river valley in Blender 2.8.

I’m pressing on with Blender, using the 2.8 beta, rather than the current 2.79 version. I figure that if I’m going to learn Blender, I might as well use the version that will be the current version when I get up to speed.

I’ll get to Blender in a minute but I’d just like to mention that I have a few writing ideas floating around in my head. I’ve completed one story and I’m mulling one story line in my head, but the characters want to do something that I’m not completely happy with. Yes, that is how it seems to me. I have little control over the characters and what they do!

The way that they want to act is within character, so I suppose I will put pen to paper, or rather, pound the keyboard, eventually. Sometime soon I’ll drop Blender for a while and switch over  to my word processor, but for now I’m still learning Blender.

https://www.freeimages.com/photo/television-studio-1-1171607
The image is from FREEIMAGES (https://www.freeimages.com/photo/television-studio-1-1171607), supplied to them by Joseph Hoban.

Blender is complex because real life 3-D objects which artists are trying to draw are complex. For instance, in real life there is rarely a single source of light. We may say that a an object in a scene is lit by the sun, but really it is lit by the sun, by the ambient light from the sky and the surroundings, and by reflections from other objects in the scene.

The image above shows a studio set up for television, and it shows multiple sources of light and the stage on which the scene, whatever it is, is to be set. The stage is illuminated by a lamp, but there is also a shadow on it. The shadowed part can be seen because it is illuminated by other lamps. Things in the unlit areas around the stage can be seen dimly because some light is reflected from the stage or it spills over from other lamps.

Lighting is complex and one of the things that Blender does is emulate some of this complexity. When someone builds something in Blender the object that is modelled is colourless and textureless. It’s like one of those dressmaker dummies that is merely a shape and a framework for the clothes to be are created on it.

No materials
Some of the lighting has been set up for this object, but not enough. No materials have been applied.

The object in the above image is illuminated by a light source (or rather the object is drawn as if it is illuminated by a light source). It stands on nothing, is surrounded by grey, and is visually it is not that impressive.

For a number of reasons I recreated the tower and this time I gave it some colour by adding colour to the background and another light source, and some ambient lighting.

Cartoon tower
Cartoonish tower, with background, something to stand on and some ambient lighting. There is some other lighting, but it is a bit dim and hard to see.

That still looks cartoonish! It’s still decidedly unimpressive, but I am, I hope, making progress. I’ve learned a lot and hope to put some of it into practise soon. I’ve watched dozens of videos, some of which helped and some of which didn’t. Some of the people making the videos are very good. Others click rapidly on the various windows and menus, leaving me confused.

Some videos seem to refer to earlier versions of the software, which means I have to figure out some of the steps that the video creator just quickly clicked over. Some show how to do specific tasks, like create a floating island, or realistic landscapes, and I have to extract from those the techniques that I need. But I believe that I’m making progress. Maybe by 2020 or early 2021…

I forgot to mention that once the model has been built and been decorated with materials and  textures, it is finished but only exists as a Blender file. To produce images, like those above, the object needs to be rendered. The 3-D object needs to be converted to a 2-D image file. Rendering of complex Blender files can take hours as it is a complex mathematical task. The above images, and the one below that I am going to leave you with, took only a minute or less.

The last image is an early version of the river valley that I started this post with. Since then I have dialled back the ambient lighting and added some “materials” to colourise it. It’s probable that I will rebuild the river valley completely.

River valley (early version)
An early version of the valley and river.

Please read my books. The paperback versions can be found Amazon, and the eBooks can be found there or at your favourite eBook store. Just search for my name, Cliff Pratt. I mainly write fantasy fiction.

Why did he do it?

Embed from Getty Images

Why do people become murderers or rapists, or even petty thieves. I mean, sure, sometimes a person could irritate you to the point where a fleeting thought of carnage crosses your mind. But most people would immediately shut down that thought and even be shocked and revolted by it. They certainly wouldn’t act on it.

Surely no one wakes up one morning and thinks “Oh, I’ll become a career criminal,” or “Oh, I’ll violently attack someone today.” It’s easier to explain when the person is immersed in a culture where crime is normal and maybe even expected of one. But there are law abiding people even within the worst of environments, where crime is common.

Embed from Getty Images

Fear of consequences is often used to try to deter people from crime, but in many cases the fear of consequences is not enough to prevent a person committing a crime. Prison may be seen as normal and expected. So called petty criminals may expect to be thrown in to jail many times in their lives and to them it cannot be much of a deterrent.

Of course, one’s better judgement can be nullified by drugs or by alcohol. Many assaults happen when the person who assaults another person is drunk or high on drugs. Other crimes like rape, burglary, and vandalism are also more likely to happen when a person is intoxicated.

Embed from Getty Images

One way that is often suggested to reduce crime is to increase the severity of the punishment, so that fear of consequences is increased. However, this has limited effect only. People still committed murder even when capital punishment was still used. When in a blind rage, if a person is mentally ill, or if the person believes that they can get away with a crime without being caught, then the consequences often do not come under consideration.

In a court of law it is assumed that the person knew that consequences and still continued with their action. In many cases I believe that this is simplistic to say the least. A person sees another person leave a phone or wallet somewhere that the first person can take it from. Often the first person doesn’t think through the consequences of the theft. They don’t even consciously think that they can get away with it. They just react to the item being accessible.

Embed from Getty Images

Also each successful theft reinforces the thief’s feeling that he or she will not be caught, so they do it again. In fact, of course there is a chance that they will be caught each time that they commit the theft, and the more times that they commit the crime, the more likely it is that they will eventually get caught.

If they are likely to get away with the crime nine times out of ten, then if they commit the crime seven times, the chance of them getting caught is better than even. Maybe one way to reduce crime is to teach criminals statistics!

Embed from Getty Images

It seems that the propensity to commit crime is inherent in human beings. It is not related to social standing, as crimes of theft and of fraud are seen to be committed by people of all social standings. The criminals, even those higher up the socioeconomic ladder tend to make the mistake of repeating their crimes, which, as I mentioned above, renders them more likely to be caught.

Of course those lower down the socioeconomic ladder commit simpler crimes like theft and violence often fuelled by alcohol and drugs, and those higher up commit the so-called white collar crimes. A person’s position on the ladder doesn’t seem to bear much relation to whether or not they commit sexually related crimes, and in fact, a person’s higher standing often seems to protect them against being caught – they are able to convince people to look the other way when such a crime is committed, by using their influence or by using their money to buy people off.

Embed from Getty Images

If the propensity for crime is to be found at all levels of society, and the punishment of criminals is relatively ineffective as deterring criminals from committing crime, what is there that we can do about it? In my opinion, not a lot. But nevertheless we need to try, if only to reduce it to the minimum possible.

That is what society, from the beginning up to the present day is trying to do, of course. The consequences of being caught committing a crime don’t stop everyone, but it is likely that they do stop some people. Over harsh penalties from crimes don’t work beyond a certain point, and this has been recognised in societies that have dumped capital punishment.

Embed from Getty Images

We try to keep down crime by locking up those who are caught committing it. Again this has only limited effectiveness as well as, effectively, targeting those at the low end of the socioeconomic ladder. A rich person who is fined for jumping a red light is likely to notice it much less than a poor person. The fines represent a much bigger portion of a poor man’s income than that of a rich man.

The only way to reduce crime to zero is to change the human race. If the genes for criminality and violence were to be bred out of the human race, then we would have no problem with crime. Women would not be raped and funds would not be embezzled. People would not drink drive, and would not bash other people.

However, the genes for criminality might be perilously close to the genes for creativity. Creative individuals are often those who break the rules, who go beyond what is allowed. Creative individuals also tend to be those who are close to the boundary between sanity and insanity. They are the eccentrics among us, the ones who do not fit in.

Maybe we could prevent crime by changing the human race, but we risk creating a society which also has no artists, no eccentrics, and essentially no Leonardo DaVincis, no Isaac Newtons, no Shakespeares, no Albert Einsteins. Society would be the poorer for that.

Embed from Getty Images

 

Oddities

Embed from Getty Images

Humans and not very good at calculating odds and how probabilities work. For instance, if we are tossing coins and we get six heads in a row, the probability of getting yet another head is still fifty-fifty. Yet people feel that after a series of heads that it is more likely that more tails than heads will turn up for a while, so that the ratio of heads to tails returns to the expected one to one ratio.

But the expected ratio of heads to tails for all subsequent tests is one to one. It’s as if a new set of tests is being started, and so any lead that has already built up is, in all probability, not going to be reduced.

This seems odd. If we have done one thousand trials and have turned up 550 heads to 450 tails, the ratio of heads to tails is about 0.818 and the ratio of heads to the number of tests is 0.55. Surely more tests will take the ratios closer to the expected values of 1.0 and 0.5? Surely that means that there will be more tails than heads in the future?

Embed from Getty Images

Well, the answer to both questions is no, of course. The ratios for the whole test may move closer to 1.0 and 0.5, but equally, they may move further away. In the extreme case, there may never be a tail again. Or all the rest of the throws may result in tails.

Interestingly, if the subsequent tests produce a series of heads and tails, the difference between the number of heads and tails stays at around 100, but the ratio of tails to heads for the whole test slowly creeps closer to 1.0 and the ratio of heads to the total number of tests closes in on 0.5 as more and more trials are done. By the time we reach two million tests, the two numbers are not very far from the expected values, being 0.9999 and 0.5000 respectively.

So, if you think to yourself, as you buy a lotto ticket “Well I must eventually win, if I keep buying the tickets”, it doesn’t work like that. You could buy a lotto ticket forever, literally, and never ever win. Sorry.

Embed from Getty Images

Lotto and sweepstakes are, I believe, a different type of gambling from other forms, such as betting on horses or poker and other gambling card games. Lotto, sweepstakes and raffles involve no element of skill, and the gambler’s only involvement is buying the ticket. Betting on horses or cards involves skill to some extent, and that skill comes down to things like working out the probabilities of a particular card coming up and the probabilities of other players having certain cards in their hands.

Both types of gambling encourage the gambler to gamble more. If a gambler doesn’t win on the Lotto he or she might say to his or herself “Better luck next time.” Of course, luck does not exist, but probabilities do, and this is a mild form of the Gambler’s Fallacy described above. Nevertheless, people do win and the winners appear on television for us all to see and emulate.

Embed from Getty Images

There’s two sorts of strategy for winning the Lotto. First there’s the “always use the same numbers” strategy, and then there’s the “random numbers” strategy. If you always use the same numbers, goes the theory, then eventually there must be a match. That’s wrong of course, since the number combination may not appear before the end of the universe.

The random number strategy argues that there is no pattern to results so it is silly to expect a particular pattern to eventuate. This strategy acknowledges the random nature of the draw, but doesn’t give the gambler any advantage over any other strategy, even the same numbers strategy. It is certainly easier to buy a randomly generated ticket than to fill in a form to purchase the same numbers every time.

Embed from Getty Images

Some people experience a run of luck. They might have three things happen to them, so go and buy a lotto ticket while their luck holds. Then is they win they attribute it to their lucky streak. It’s all nonsense of course. They conveniently forget the many, many times that they bought a ticket because of a lucky streak, only for the ticket to be a loser.

The proceeds from the sales of lotto tickets don’t normally all go to holders of winning tickets. Firstly the operators of the system need to recoup their costs. It’s not cheap to own and operate those fancy machines with the tumbling balls and it also costs to employ the people to check that the machines are fair.

Embed from Getty Images

If one of the balls is dented, will that affect the probability of that ball being selected? Maybe, just a little, but the draw should be fair so those providing the lotto equipment spend a large amount of effort to ensure that they are fair, and the costs of that effort must come out of the prize funds.

Secondly, the state or maybe the lotto organisation itself will often withhold part of the lotto sales takings for local or national causes, such as cancer research, or societal things, like the fight against teen suicide. The money for humanitarian causes is deducted from the prize funds.

Embed from Getty Images

One of the humanitarian causes is often the fight against problem gambling. It’s ironic and somewhat appropriate that funds from gambling are used to combat problem gambling. It seems that some people get such a thrill from gambling that they use all their, then borrow or steal from others to continue to gamble.

They invoke the Gambler’s Fallacy. They suggest that their luck must change sooner or later. It doesn’t have to, and may never change, but they continue to spend money on their gambling. They also don’t take account of the fact that they might win, eventually, by sheer chance, but it is unlikely that their winnings will cover what they have already gambled away. They have a tendency to believe that one big win will sort things out for them. It won’t of course.

Embed from Getty Images

So, the only true fact about Lotto and similar draw is that you have to be in to win. But just because you are in doesn’t mean that you will win. You probably won’t. The best way to treat Lotto and other similar games is that you are donating to a good cause and you might, but probably won’t get something back. So, I’m off to buy a lotto ticket. I might win thirty million dollars, but I won’t cry if I don’t.

Embed from Getty Images

 

Round it up!

Circle of Life
Circle of Life

Quite often a visit to Wikipedia starts of a train of thought that might end up as a post here, and often I forget the reason that I was visiting Wikipedia in the first place. However in this case I remember what sparked my latest trip to Wikipedia.

I was looking at the total number of posts that I have made and it turns out that I have posted 256. This is post number 257, which is a prime number incidentally. To many people 256 is not a particular interesting number but to those who program or have an interest in computers or related topics, it is a round number.

US 256
US 256

A round number, to a non-mathematician is a number with one or more zeroes at the end of it. In the numbering system with base 10, in other words what most people would considered to be the normal numbering system, 1000 would be considered to be a round number. In many cases 100 would also be a round number and sometimes 10 would be as well.

In the decimal system, which is another name for the normal numbering system, the number 110 would probably not usually be considered a round number. However, if we consider numbers like 109, 111, 108 and 112, then 110 is a round number relative to those numbers. Rounding is a fairly arbitrary thing in real life, usually.

We come across round numbers, or at least rounded numbers in the supermarket on a daily basis, if we still use cash. Personally I don’t. I recall when the one cent and two cent coins were introduced people were appalled that the supermarkets would round their bills to the nearest convenient five cents.

5 lirot
5 lirot

 

So a person would go to a supermarket and their purchases would total to, say, $37.04. The cashier would request payment of $37.05. Shock! Horror! The supermarket is stealing $0.01 off me! They must be making millions from all these $0.01 roundings. In fact, of course, the retailer is also rounding some amounts down too, so if the bill was $37.01 the customer would be asked to pay only $37.00. So the customer and the supermarket, over a large number of transactions, would end up even.

Then of course the 5 cents coins were removed and this added an extra dilemma. What if the total bill was $37.05? Should the customer’s bill be rounded to $37.00 or to $37.10? This is a real dilemma because, if the amount is rounded up, then the supermarket pockets five cents in one ten cases, and if it is rounded down the supermarket loses five cents in one in ten cases. If the supermarket a thousand customers in a day, one hundred of them will pay five cents more than the nominal amount on their bill, meaning that the supermarket makes a mere five dollars.

Big Money
Big Money

The emotional reaction of the customer, though, is a different thing. He or she may feel ripped off by this rounding process and say so, loudly and insistently. Not surprisingly most supermarkets and other retailers choose to round such bills down. Of course, all the issues go away if you don’t use cash, but instead use some kind of plastic to pay for your groceries, as most people do these days.

There are degrees of roundness. In one context the number 110 would be considered round, if you are rounding to the nearest multiple of ten. If you are rounding to the nearest multiple of one hundred, then 110 is not a round number, or, in other words a rounded number. If we are rounding to the nearest multiple of three, then 110 is not a rounded number but 111 is (111 is 37 multiplied by 3).

Binary Backdrop
Binary Backdrop

Real numbers can be rounded too. Generally, but not always, this is done to eliminate and small errors in measurement. You might be certain that the number you are reading off the meter is between 3.1 and 3.2, and it seems to be 3.17 or so, so you write that down. You take more measurements and then write them all down.

Then you use that number in a calculation and come up with a result which, straight out of the calculator, has an absurd number of decimal places. Suppose, he said, picking a number out of the air, the result is 47.2378. You might to choose to truncate the number to 47.23, but the result would be closer to the number that you calculated if you choose to round it 47.24.

Currency Symbols
Currency Symbols

A quick and easy way to round a real number is to add half of the order of the smallest digit that you want to keep and then truncate the number. For the example number the order of the smallest digit is 0.01 and half of that is 0.005. Adding this to 47.2378 gives 47.2428, and truncating that leaves 47.24. Bingo!

Another way of dealing with uncertain real numbers such as results from experiments is to calculate an error bound on the number and carrying that through to the calculated result. This is more complex but yields more confidence in the results than mere rounding can.

Tube
Tube

To get back to my 256th post. Why did I say that this is a round number in some ways? Well, if instead of using base 10 (decimal), I change to using base 16 (hexadecimal) the number 256 (base 10) becomes 100 (base 16), and those trailing zeroes mean that I can claim that it is a round number.

Similarly, if I choose to use base 2 (binary), 256 (base 10) becomes 100000000 (base 2). That is a really round number. But if I use base 8 (octal), 256 (base 10) becomes 400 (base 8). It’s still a round number but not as round as the binary and hexadecimal versions are, because it start with the digit 4. As a round number its a bit beige.

It’s interesting (well it is interesting to me!) that there are no real numbers in a computer. Even the floating point numbers that computers manipulate all the time are not real numbers. They are approximations of real number stored in a special way (which I’m not going to into).

General Double Precision Float
General Double Precision Float

So when a computer divides seven by three, a lot of complex conversions between representations of these numbers goes on, a complex division process takes place and the result is not the real number 2.333333…. but an approximation, stored in the computer as a floating point number which only approximate, while still being actually quite accurate.

One third
One third

 

Once a week

English: Lunar libration. see below for more d...
English: Lunar libration. see below for more descriptions Français : Librations de la lune. Voir une description détaillée en dessous. (Photo credit: Wikipedia)

I’ve been pondering the topic of ‘the week‘. Not the ‘topic of the week’. The week, as in seven days. It’s an unusual number to use as a unit for a length of time, as it is a prime number of days, and this makes using fractions of a week a bit tricky. Half a week is 3 and a half days long, so it’s not usual to, for instance, agree to meet someone in ‘half a week’.

No, we say ‘See you in three days’, or four days. We might say ‘this paint will take 2 and a half days to fully dry’, but this is a bit odd. We’d usually say something like ‘this paint will take between 2 and 3 days to fully dry’. We usually treat days as ‘atomic’ when counting days. The number of days is usually an integer, although we could break days down and use fractions or real numbers with them.

Unusual Calendar
Unusual calendar. 12 months 9 days in week

The fact that the number of days in a week is a prime integer also makes converting from weeks to days and days to week interesting. Quick, how many days in seventeen weeks? The answer is 119. How many weeks is 237 days?  The answer is 33 with six days left over. It’s not easy.

Four weeks is 28 days, which is approximately a lunar cycle. It is also very approximately one month. There are approximately thirteen 28 days period in a year, assuming a 365 days year which is approximately correct. This is probably why some calendars have thirteen months.

Lunar eclipse
Lunar eclipse

The lunar cycle is around 29 and a half days, whereas the month defined as one twelfth of a year is around 30 and a half days. Nothing fits! The month is based on the lunar cycle, and the ancients noticed that that the twelve lunar cycles is 354 days which was close to the 365 and a bit days that comprise a year.

So, they decided to make it fit. They divided the year into 12 months, which left them with bits of days just lying around. This was obviously untidy so they scrunched up the bits into one days and tagged them onto the various months more or less at random. The final left over bit that they ended up with they ignored.

Monthly bus pass
Monthly bus pass

That’s how we ended up with mnemonic rhyme “30 days hath September, April, June and November…” with that horrible line that doesn’t scan. That’s rather appropriate really, as the reason that the rhyme is needed is because the days don’t fit properly into the months. It’s an uneven rhyme for an uneven scheme.

The ancients ignored the odd bit of a day that was left over until someone noticed that the year was still sliding out of synchronisation with the seasons. So they added or took away a day or two here and there in special, short or long years. Problem solved.

Leap year 1908
Leap year 1908

Well sort of. They ended up with a super complex list of rules for working out how many days there are in a month, where to fit extra days into the calendar, and when to fit them in. Horror!

Finally scientists decide to cut through all this confusion and define a second by using an atomic clock. Providing you don’t accelerate the clock to a significant fraction of the speed of light and keep it at absolute zero. Easy!

First atomic clock
First atomic clock

Again, sort of. The standard second times sixty give a standard minute. The standard minute times sixty gives the standard hour. The standard hour times twenty four gives the standard day and the standard day times seven gives the standard week. Yay, you might say.

Unfortunately the actual day and therefore the actual week is not exactly equal to the standard day or week. It would be quite legitimate to claim “Wow, this is a long week, it’s 0.608111.. standard seconds longer than a standard week”. But don’t expect much sympathy.

Leap second 2016
Leap second 2016

Seven days is actually a pretty reasonable length to a week. We divide it into “the weekend” and “the rest of the week”. If it was a couple of days longer, it would be a long time between weekends. We’d probably be tempted to add an extra day to each weekend, or maybe alternate weekends…. But now we’re getting complicated again.

If the week was shorter, we’d probably get less work done. If the week was five days and we still had a two day weekend then time available for work would be about 17% less. Of course five day working weeks are fairly recent in historical terms, but I’m not going to work out the numbers for a 6/7 working week and a 4/5 working week.

Aztech Sun Stone Replica
Aztech Sun Stone Replica

Speaking of work, and assuming that most people would not work unless they have to, we have developed various coping strategies. We count the days to the weekend. “Only three more days to the weekend.” Tomorrow is Thursday and that means only one more day to the weekend.”

We designate Wednesday as “Hump Day”, since it is the middle of the week and if we reach Hump Day before having a breakdown or perhaps killing someone, that’s a win. There’s only half the week to go and we’ve broken its back.

We celebrate Fridays, often with a quick drink, then shoot off to enjoy the weekend. We come in on Mondays, faced with five more days of toil. On Tuesdays, we’ve at least knocked off one day, but it’s still a bit beige. Wednesday is Hump Day and we’re halfway there! When Thursday comes we’re almost there, and Friday is relatively easy. It’s practically the weekend, when we block out the thought of Monday all together if we can.

TGIF - switch off
TGIF – switch off

The week has a sibling called the “fortnight”. Two weeks, as a chunk. At one time the fortnight was usually reserved for a summer holiday. A fortnight at the beach or the bach. Time away with the kids. Idyllic golden weather by the sea. Of course, we only remember the good times, and forget the bad ones, but still it would be summer, it would be fairly warm, and the weather is usually better in the summer.

Weeks are the medium sized sections of our lives, often used to split up the humdrum from the pleasant parts of our lives. We should appreciate our weeks, no matter how many standard seconds long they are.

Girl on a swing
Girl on a swing