Thanks Scotland

Whichever way you voted I want to thank all the Scottish people for benefiting the union as a whole. The consequence of your referendum is that the English, Welsh and Northern Irish will now also get a much bigger say in how they are governed at a local level, as the UK reinvents itself into a modern federal democracy, similar to the USA.

Now we have to address the other big question that’s quickly coming our way – what to do about Europe…

Posted in Observations | Leave a comment

So, what’s it going to be, Scotland?

Posted in Media, News | Leave a comment

The Future of the UK, Scotland, New Britain, and The European Union

No more Scotland in the UK?So, the latest poll shows that support for Scottish independence from the UK is rapidly growing, and has now passed the 50% required to win in the upcoming referendum – and increasing by about 5% a week. If this rate continues, an overwhelming majority of around 60% of Scots will vote for separation from the hundreds of years old union.

First of all, as a born and bred English southerner, I wish the Scottish people success and prosperity with whatever decision they take. In fact it must be very exciting to contemplate the possibility of such a massive change, and the reclaiming of so many powers from Westminster. Fail or prosper, the future success of the Scottish nation will rest on their own endeavours and their own choices, and that must be a very appealing and satisfying prospect.

I think if I were Scottish I would choose independence, for the very same reasons that most British voters recently voted for the UK Independence Party in the European elections and who, in next year’s general election, are likely to return this party into a position of holding the balance of power, forcing the Liberal Democratic party (currently in a ruling alliance with the Conservatives) into fourth place

If the UK didn’t have a first past the post system, UKIP might even win the general election outright, with over 50% of the vote. However, our system favours incumbents, who change boundaries to remain in power, and probably 65% of the vote would be necessary for a minority party to obtain a landslide. Still, not unachievable – but probably not this time around.

We are fed up with far away bureaucrats ruling our lives

What the British as a whole are saying they want is more local control over what affects our lives. The Scottish want London to keep its fingers out of Scottish business, while the British as a whole want Brussels to do the very same thing. It seems that while business people love the idea of ‘ever closer union’, because it helps them to become ever richer, the general populace don’t, because these unions results in more rules and fewer freedoms, and we have all simply had enough of petty bureaucracy costing us time and money. We don’t like being pushed around by people we see as having no business interfering in our lives.

I do wonder whether Scotland working together with an Independent UK, withdrawn from the EU would be stronger than the two separated, but I believe the Scots actually want to remain in the EU after independence, so that would not have been an option. However if, as appears likely, Scotland votes to leave the UK, then it means the pro-European Scots will not be able to vote in the 2017 European referendum for UK withdrawal from the EU, and that will give a huge boost to UKIP.

Speaking of which, when (or maybe it’s still if)  the English and Welsh see how the Scottish manage to gain their independence, they will want British independence from the EU more than ever. We will think that if Scotland can do it, so can the rest of the former UK. So, for me, the indications clearly are that the UK as we currently know it will be no more by next year, and by 2018, the remaining member countries of the UK will be independent themselves, from the rest of Europe.

After separation: The question of names

And then, what will be our respective names? Well, obviously Scotland will be Scotland, that’s an easy one. But the UK? It will no-longer be as united, so United Kingdom is surely now out of the question. How about Great Britain then? Well, it won’t be as great as it was with Scotland out of the union, so that won’t be fitting either.

Also I seriously doubt any contraction of Wales and England will work (Wengland, Walesland, Engales, etc), so I see no choice remaining, other than that the UK will become simply ‘Britain’. Many of us refer to ourselves a ‘Brits’ anyway, so I think we’ll easily get used to our new country name, which will be logical and fitting.

The future of Scotland and Britain (and the EU)

The UK, or Britain as it may be known, has a long series of past connections with former countries it once occupied. But its former colonies have all been given their independence and obtained self governance. And now there remains a very strong connection in the form of the Commonwealth. A voluntary organisation of 53 independent countries with a population of about 2.2 billion people (about a third of the world). In contrast to this the USA has about 315 million people, and the EU around 500 million.

The Commonwealth does many things. It just recently marked a very successful Commonwealth games (in Glasgow, Scotland), and the Charter of the Commonwealth is every bit as important as the US Constitution, or the EU’s Charter of Human Rights, but there is no desire for uniting the Commonwealth countries into any larger entity. The aim is simply to work together to benefit the lives of all Commonwealth members.

And that’s where I see the future of new Britain (hey, maybe New Britain could be our new name), to strengthen Commonwealth links, build up commercial and trading relationships, and prosper as the biggest partnership of its kind in the world.

The European Union doesn’t have such a relationship, but the European countries do have each other. Great, so let them unite. Europe will continue absorbing satellite countries until it fully unites politically into one large country, like the USA and its 50 states. Interestingly, Scotland will very likely end up a part of the expanded EU, handing its hard won powers back, but this time to Brussels.

Britain, however, doesn’t need Europe when we have the Commonwealth. Especially when there is no requirement to unite or follow orders issued by a central bureaucracy, just the commitment to work closely on world issues for the benefit of all. We will all retain full local control over our own laws and the vastly different ways of life of our different peoples, and still enjoy the benefits of cross-border collaboration and trade. The best of both worlds.

Posted in Articles, Observations | Leave a comment

Has the popularity of PHP (the most-used web server language) now peaked?

PHP and JavaScriptAfter a number of years of consolidation, in which users flocked from Perl to PHP because it was so much faster, easier to use, and could handle more connections at a time (although Perl nowadays is extremely fast and sleek, but I think it’s had its day), there’s now another similar change looming on the horizon.

This time the instigator is the growth of HTML5, in which you need to master JavaScript in order to achieve the more fun and useful features, such as geolocation and accessing the canvas. This has caused an incredible (and mostly unforeseen) rise in the popularity of JavaScript, which over the last five years has shot far ahead of all other web development languages, yes beating even Java and Ruby in popularity.

And while PHP has shown slow growth over the same period (presumably at the expense of Ruby and Python, which are both declining in popularity), I think it has probably peaked and is even starting to decline. Yet, just a few years ago most people would have thought PHP was going to dominate the web, and never would have thought that a language primarily developed to run in a client environment could become a challenger to PHP.

But that’s what seems to be happening with the likes of Node.js, which uses the Google Chrome JavaScript run-time to run on a web server (in place of a language such as PHP), providing highly scalable and ultra fast applications. Even if you haven’t used Node.js but think about the concept for a minute, you’ll begin to understand the product’s success. You see, why learn two languages for server/client communications, when you need to learn only one – namely JavaScript?

So where do I see PHP in five years time? Well, it will still be an important technology, simply because it has the momentum of being used by something like 60% of all websites. But I believe that JavaScript is going to migrate fairly and squarely to the server environment and, whether or not Node.js remains at the forefront, I believe JavaScript will become so widely used that it will continue to increase its already impressive lead in popularity over the other competing languages, for a considerable number of years to come.

So what should you do as a developer (or would-be developer)? Well, right now you absolutely need to know one or more of the main server languages, and for me the best choice would be PHP. But you should also become expert in using JavaScript too. Not only will learning it pay dividends in the browser, in the future you’ll be able to draw on the same skill set for your server programming too. Fortunately both these languages (and other technologies you should know) are covered in depth in my book Learning PHP, MySQL, JavaScript, CSS & HTML5.

Posted in Articles, Observations | 4 Comments

What if… well, you decide…

Posted in Media, Observations, Poetry / Prose | Leave a comment

Primes, Pseudo Primes, And Yet More Primes!

Prime numbersIt’s possible to tell whether or not a number is prime in a number of ways. You can crunch through all possible factors of a number until you have a definitive result (which can take an exceedingly long time for very large numbers), or you can use a formula to return a very high level of probability about whether a number is prime. Recently I’ve been looking into both these methods.

In this post:

  • How to create huge arrays of primes quickly using JavaScript
  • Graphically displaying and animating prime numbers
  • How to test for the probability of primality (Fermat’s Little Theorem)
  • Numbers that resist these tests (Pseudo Primes and Carmichael Numbers)
  • How to overcome this resistance

Finding Primes With JavaScript

At its simplest, to find all prime numbers between 1 and n in a language such as JavaScript, you can use code like this:

function getprimes(n)
{
  var p = []
  for (var j = 1 ; j < n ; ++j)
    if (isprime(j)) p.push(j)
  return p
}

function isprime(n)
{
  for (var j = 2 ; j <= Math.sqrt(n) ; ++j)
    if (n % j == 0) return false
  return true
}

The first function builds an array of prime numbers, which it returns in the array p[] by calling the second function to test all values of n for primality, up to the square root of n. The square root of n is chosen because all factors come in pairs and we only need to check the lowest of each pair. So (for example) the number 64 has the pair of primes 8 and 8, so you can clearly see that, therefore, the square root of a number is the largest that the smaller of a pair of primes can be.

It is possible to improve on code such as this because we know that all composite (non-prime) numbers can be created with a pair of prime factors. Therefore the previous code can be updated to only test for prime factors, like this (with the modifications shown in blue):

function getprimes(n)
{
  var p = []
  for (var j = 1 ; j < n ; ++j)
    if (isprime(p, j)) p.push(j)
  return p
}

function isprime(p, n)
{
  for (var j = 1 ; p[j] <= Math.sqrt(n) ; ++j)
    if (n % p[j] == 0) return false
  return true
}

The second function is also given access to the array p[] by adding it as an additional argument, so that it can look up previously determined prime numbers for use in its primality tests.

Now if, for example, the number being tested is 36, instead of checking possible factors 2, 3, 4, 5, and 6 (the square root of 36), only the values, 2,3, and 5 will be tested since they are the only primes numbers equal to or less than 6. This has saved two tests (4 and 6). And the bigger the number, the more tests you save until you can ignore about 5 in every 6 or so.

Indeed, you can also improve the main loop by ignoring all even numbers plus those that are divisible by 5, like this (with updates in blue):

function getprimes(n)
{
  var p = [1, 2]
  for (var j = 3 ; j < n ; j += 2)
    if (j == 5 || j % 5 != 0 && isprime(p, j)) p.push(j)
  return p
}

function isprime(p, n)
  {
    for (var j = 1 ; p[j] <= Math.sqrt(n) ; ++j)
      if (n % p[j] == 0) return false
    return true
  }
}

In this version of the function, the p[] array is now pre-populated with the values 1 and 2 since they work slightly differently to the others, so they are hand-inserted. Then the loop starts at the number 3, with the (other unusual) number 5 accepted, but not any other multiples of 5. And now the code is fairly efficient, except that the square root function is not optimized for this particular use, and so a faster version of the inner function would be to remove the expression p[j] <= Math.sqrt(n), replacing it with p[j] * p[j] <= n.

You can now call this function with the following command (for example) to return the prime numbers up to 100, which will then be displayed in the current browser document:

document.write(getprimes(100))

The result of this command will be as follows, and I have tested it on an i7 PC with values of up to 10 million (which are calculated in about a second), and 100 million (which takes around 9 seconds):

1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

The PrimeDancer Web App

My new web app, PrimeDancer.com uses the preceding code to generate the primes it displays and animates. It’s a vastly improved and speeded up version of my earlier prime spiral animator, which now uses simple sliders to adjust the speed, direction, and zoom. It also lets you click in the animation to detect all the numbers in a sequence of a spiral arm, or use the sliders on the left to find them. When running the program looks like this, and I think you’ll find it rather fun to play with:

Prime Dancer

I find it fascinating (and quite relaxing) to watch all the possible patterns resulting from the distances between potential plot points on the spiral being slightly changed with each frame. What happens is that, for example, all the even numbers often reveal themselves as spiral gaps, but then so do multiples of three, four, five, and all the way up, as and when they are lined up above above each other in each turn of the spiral.

What’s more you can see multiple gaps at a time causing ‘interference’ patterns, and a tremendous amount of complexity reveals itself. One of my first theories was that where a spiral arms was particularly flush with pixels, it might be possible to follow that arm out like a rich vein of coal. Indeed when I did this it was the case, but only for a while. The further out you go the more the ratio of primes to composites returns back to the norm. Still, as you’ll see, there are other ways of finding seams of primes.

So this app is probably now more of a toy than a maths experiment that will yield new information, but I think it’s unique, and primes have never been displayed in quite such an interesting and dynamic manner before.

Continuing The Search For Prime Numbers

But why all this tinkering in the first place, you might ask? Well, things like Internet security rest on the employment of incredibly large prime numbers, so any new discoveries in this area could lead either to new, more powerful encryption systems, the cracking of current techniques, or even both. So it’s a fun (and potentially profitable) area to study.

The trouble is that (fast as it is), this type of code will never be good enough to identify enormous prime numbers quickly enough for improving (or hindering) ecommerce and private communications (even when written in compiled C or hand-coded assembly language).

A Better Way to Test For Primality

Thankfully, though, there’s a better way (in fact there are several of them), the first of which was invented (or perhaps discovered) all the way back in the 1600s by the mathematician Fermat (yes, he of the famous Last Theorem). What is less known is that Fermat also came up with what is called his Little Theorem, in which the primality of a number can be predicted with a very high rate of probability by selecting what is termed a coprime number, and then  raising this coprime to the power of the number to be tested. The coprime number can be any integer less than the one being tested, and need not be prime.

So, for example, to test the number 7, you could choose the coprime base value of 4 and raise it to the power of 7 (which is 4 × 4 × 4 × 4 × 4 × 4 × 4). If you can then subtract the coprime from this result such that the final result is exactly divisible by the number being tested, then the number could well be prime. It looks like this: (47 – 4) / 7. Or like this in JavaScript:

if ((Math.pow(4, 7) - 4) % 7 == 0)
  document.write('Possibly prime')

In this code, the % instruction divides by 7 and returns only the remainder (modulus) of the operation. So if the result is zero there was no remainder and so the the test is passed. If, however, there is a remainder then the number is definitely composite.

The Problem With Pseudo Primes

Interestingly, when applying Fermat’s little theorem, a few very strange numbers crop up which look very much like prime numbers to it, but they aren’t – and so they are given the title pseudo primes.

Some examples of Fermat’s pseudo primes include the numbers 341, 561, 645, 1105, 1387, and 1629. Actually there’s an infinite number of them, but you can see that they are fairly uncommon.

However, by changing the coprime used in the theorem to a different base number, and re-running the test, you can almost always weed out these pseudo primes to narrow down your certainty.

The Resistant Carmichael Numbers

But you can only narrow down to an extent, because a subset of these pseudo primes (known as the Carmichael numbers after the mathematician who discovered the first one), resist the Fermat Little Theorem test in every base you choose:

In number theory, a Carmichael number is a composite number
n which satisfies the modular arithmetic congruence relation:
b n ≡ b (mod n) for all integers 1 < b < nWikipedia

This set of numbers includes 561, 1105, and 1721, and has an even rarer occurrence (only about 1 in 2.5 million). Nevertheless, these numbers are also infinite and are a considerable nuisance to cryptographers, who have now developed some very advanced mathematics to deal with this issue.

Before moving on to looking more deeply at these pseudo primes, though, let’s take a moment to write a program to simply map all prime and composite numbers onto a spiral, in a simpler version of my PrimeDancer App, like this:

<canvas id='canvas' width='630' height='630'></canvas>
<script>
  var E = document.getElementById('canvas'),
      C = E.getContext('2d'),
      P = getprimes(1024),
      j, x, y

  for (j = 1 ; j < 1024 ; ++j)
  {
    x = 315 + Math.sin(j) * j * .3
    y = 315 + Math.cos(j) * j * .3

    if (isprime(P, j)) C.fillStyle = '#00f'
    else               C.fillStyle = '#faa'

    C.fillRect(x, y, 2, 2)
  }
</script>

This code uses a 630 × 630 pixel HTML5 canvas, onto which the first 1024 numbers are plotted by simply calculating the sine and cosine of of each number to rotate it a distance according to its size. Each consecutive number is then plotted slightly further out from the center of the canvas in either a salmony color for composites, or in blue for prime numbers.

This code obviously includes some HTML and the getprimes() function from earlier, but these are not shown. The result of running this program, which you can test for yourself here, is shown below:

Number Spiral

The Chinese Hypothesis

Now let’s have some fun and slightly modify this code to enforce a variation of Fermat’s Little Theorem (known as the Chinese Hypotheses) on all these plot points, like this (with the changes highlighted in blue):

x = 315 + Math.sin((Math.pow(2, j) % j) * j * .3
y = 315 + Math.cos((Math.pow(2, j) % j) * j * .3

This time when you run the program the various plot point rotations are first vastly increased in size, and then restrained back again, causing spokes of point clustering around the circle. The result looks like this, which (for want of another word) I’ll call a Chinese Spiral:

Chinese Spiral

Holy cow Batman. See how those primes just lined right up for us? And, interestingly, how many of the composites tried to also get in on the act along a number of other arms too (and many didn’t, which is also interesting). What happened is that the primes got in an orderly line because the expression used returned a modulus of 2 for every one.

Unfortunately, though, the Chinese Hypothesis also suffers from the pseudo prime problem. Let me illustrate this by running all the numbers from 1 to 1024 through the Chinese Hypothesis

for (j = 0 ; j < 1024 ; ++j)
  if (Math.pow(2, j) % j == 2)
    if (!isprime(P, j))
      document.write(j + ' is pseudo prime<br>')

When you run this code the result is as follows:

341 is pseudo prime
561 is pseudo prime
645 is pseudo prime

Aha – we have found Fermat’s first three pseudo primes, and also the first Carmichael number (561). OK, so let’s tighten up the code a little and use the trick Fermat described, of testing using one or more additional bases, like this (with the change highlighted in blue):

for (j = 0 ; j < 1024 ; ++j)
  if (Math.pow(2, j) % j == 2 && Math.pow(2, j) % j == 2)
    if (!isprime(P, j))
      document.write(j + ' is pseudo prime<br>')

Now when you run this code, no pseudo primes are returned – all prime numbers up to 1024 are successfully recognized, as confirmed by the isprime() test. I’d like to take this example further, but the limit of JavaScript’s Math library is reached at powers of 1024. So that will have to wait until I’ve written (or borrowed) a library for dealing with exceptionally large numbers.

A Possible New Angle?

But what I find interesting is that I thought the Carmichael numbers were supposed to be resistant to all base coprimes supplied to Fermat’s Little Theorem. But it seems that by using the Chinese Hypothesis variant with a different base, you can weed out (at least some of) the Carmichael numbers. Any mathematicians care to investigate this – it could possibly be significant?

Anyway, that’s enough messing around with primes for the moment – I have to get back to recording the videos for my new CSS book due for publication by McGraw-Hill in January. But I’d welcome distractions in the meantime if you have any ideas or thoughts to share in the comments :)

Posted in Articles, Features, Observations | Leave a comment

Animals are warm blooded because chocolate

Chocolate keeps us warm, or is it the other way?Actually, because fat, to be more precise. As long-time readers will probably know I have so far lost over 50 pounds and reversed pre-diabetes by eating a ketogenic diet, in which carbohydrates are kept to a minimum, replaced with greater amounts of fat. This is the diet that Dr Atkins first made famous, but which is nowadays more likely to be called Paleo.

Anyway, after a trip to the London Natural History Museum this weekend, I got to thinking about why humans (and all mammals) are warm blooded. According to Wikipedia it may be because it helps us to fight of fungal infections.

Biologists agree that being warm blooded also helps us keep mobile in the cold – so it would have been a survival trait during ice ages. But being warm blooded requires a far greater intake of energy compared to a cold blooded creature, so there must be more to it than that for evolution to have forced this greater requirement for food on us.

Or was it maybe the other way around? For example, why is it that most warm blooded animals have temperatures just warm enough to melt chocolate, or many other fats that are solid at room temperature? Could it be that the ability to properly digest fat was a survival trait, because creatures that were warmer could better liquify this fat and process the energy more quickly and efficiently?

Therefore, did warm blooded animals continue to evolve higher and higher temperatures until just past the point at which they could eat solid fats, and keep them liquid during the digestion process – and no further, because higher temperatures would be wasteful of food, having no other purpose?

This would explain why the body temperatures of warm blooded animals are all similar, and not much higher than they are – they are just sufficiently warm to digest solid fats in the most efficient manner, as you will know if you’ve ever placed a piece of chocolate on your tongue and felt it melt – or even in your hands if you keep it there too long.

Is this, then, yet another indication that human beings evolved to eat fat as our main food source, and that carbohydrates in plentiful quantities are a modern product that our bodies are simply not yet adapted to deal with, other than to store carbs as fat – which is what we have done for millennia to store energy for the winter?

So, there you have my latest theory: People are warm blooded because chocolate :)

Posted in Articles, Observations | Leave a comment

Dancing With Bits

BitDancerFollowing on from my recent mathematical investigations into infinities and prime numbers, I’ve branched out into playing with irrational numbers such as the square root of 2, e, and π – numbers whose fractional part is infinite – attempting to create new methods of detecting any hidden patterns in them.

So far, I haven’t had much luck, but then it’s early days and I didn’t expect to discover anything so quickly – and at my first attempt. However, I have come up with some fascinating results showing both the tremendous ‘chaos’ achievable from simple strings of binary digits, and an enormous amount of unexpected and complex symmetry too.

When I decided to look into irrational numbers the first big decision I made was to ignore base 10 or any other base higher than 2 because, it seemed to me, that binary is the fundamental base, and if any patterns are to be found they are mostly likely to be discovered in that base. I could be wrong, though, but I asked myself why would the universe choose to hide its wonders only within a base 10 number system? Well, you have to draw the line somewhere, but maybe later on I can start moving up the bases and seeing if anything different emerges.

BitDancerAnyway, with that choice made I then set about converting a range of irrational numbers to binary, and started thinking about how I was going look for patterns in them. Obviously, the way numbers that follow a decimal (or binary) point work, is that each sequential digit is a factor of the base smaller than the previous one

In decimal the digits after the point are 10ths, then 100ths, then 1000ths and so forth, while in binary they are halfs, quarters, eighths, and so on. Therefore, to examine these sequences of numbers for patterns in any meaningful way, the relationships of scale between each binary digit (bit) to the ones before and after it needed to be taken into account.

But with fractional numbers scaling down in size so quickly, any visualization would rapidly dwindle down in size, so I needed to find another way of giving a relationship to the numbers, and decided to construct a model in which each bit is linked to the next by a line, and I would use different movement values to represent scale. However, because all lines would otherwise be the same length, there would be little indication of bit values themselves (or at the most, lines of only two different lengths for the digits 0 and 1). So I chose to make the lines longer whenever strings of two or more of a bit appeared in sequence – the longer the sequence, the longer the line.

BitDancerThen, to indicate how the lines relate to each other, I chose to rotate each subsequent line by a small amount relative to the previous one. And to avoid the resulting model overly wrapping around on itself, I made every alternate rotation go in the reverse direction. And that is essentially what you will see when you run the program.

If you examine the output closely, you’ll see that the model comprises a long chain of lines connected at ‘hinges’, each rotated a little bit more than the previous one, and with each subsequent line alternating between using a clockwise or counter-clockwise direction for rotation.

To make things even more interesting, I chose to animate the result by placing the model in a loop, in which the rotation amount slowly changes over time. The reason for this is that one particular degree of rotation might show more of a pattern than another. Plus, to test my theory that there may be patterns yet undiscovered, it would be necessary to test all the possible angles of rotation anyway.

BitDancerA few additional tweaks later, such as adding in a camera viewpoint that tracks the model, zooming in and out to keep as much of the animation in full frame view as possible (with a moving and zooming background too), line thickness and alpha transparency depth cues, and finally some keyboard controls, and the program was complete.

Sadly, though, it seems that the four irrational numbers I have so-far tested (π, e, the golden ratio, and the square root of 2) have not yet yielded any discernible patterns (up to 512 bits), other than amazingly complex and beautiful examples of ‘chaos’ in action.

Anyway, to see what would happen if a pattern were found, I performed a final tweak to the program that made it able to create strings of binary from repeated random sub-strings. The results blew my mind with the symmetry that emerged, in what I can only describe as an ever-changing ‘dance’ (as you can see), that even displays 3D effects (with no 3D algorithms).

BitDancer - displaying PiSo now it looks as if, by using this technique, if there are any patterns in irrational numbers, they could well be detectable via this process, although not the first 512 bits of the ones I have tested so far. However, by adding more and more bits, patterns may emerge further down these numbers.

I have versions of the program that go up to 250,000 bits. They run quite slowly, and I haven’t seen anything noteworthy as yet. But who knows whether even further along, the numbers may exhibit interesting effects. Or maybe a pattern might be discovered if every other bit were tested, or every third, or bits were selected via a logarithmic progression, and so on. If there is a pattern anywhere, I believe this process may be the type of program that could detect it, even if it turns out necessary to start running up the bases to do so.

In the meantime, BitDancer, the program I created for this is a fascinating mathematical toy that can create a myriad of amazing effects. I hope you get a chance to play with it – and spend a few minutes examining the different types of patterns possible by pressing the keys shown.

BitDancer – Playing with Bitstrings

BitDancer
 

Posted in Articles, Features, Observations | 1 Comment

Try Prime Spirals for Yourself

Prime Spiral AnimationI’ve spent the last few days refining my prime spirals software to the point that it can now display all prime numbers, or subsets such as those separated by a distance of 2, 4, or other numbers, or primes that come in groups of three, four or more, and so on. I also substantially speeded up the animation and provided a set of keyboard controls.

With this program it’s now possible to explore this whole new world (at least to me) of prime spirals in far greater depth. For instance, every type of prime grouping I have so far tested will form spiral patterns. So, for example, if you plot only groups of three primes that appear in combinations of 2 or 4 numbers from each other (separation of groups of three by a distance of 2 only appears with the group 3-5-7 – so 5-7-11 is accepted in this case, as is 7-11-13, and so on), you still see them form spiral arms.

This suggests that if you were to follow those spiral arms outwards, you could more closely predict where you were likely to find further such groupings. In fact, by following the spiral arm of any grouping it may be possible to substantially narrow down the set of numbers to be checked to find any particular type of prime grouping – or even simply single prime numbers.

And I have a conjecture that by drawing a spiral that includes a known prime factor of a number, there may be a way to narrow down partner prime numbers to crack encryption systems. This is an area I haven’t yet looked into, but which I think is prime for research :)

Anyway, you can play with the program by visiting the URL below, and use the following key presses to control it:

  • [1]-[9] Display only primes at a distance of 2 times the key press from each other. For example, [1] displays twin primes, [3] displays primes separated by 6 numbers, and so on, and [0] displays all primes again.
  • [Ctrl][2]-[5] Display only those primes that appear in clusters of 2, 3, 4 or 5 (each separated by a maximum of 4 numbers). Press [0] to display all primes again.
  • [Alt][0]-[9] Change the animation speed from fastest to slowest.
  • [Shift][0]-[9] Change the pixel size from smallest to largest.
  • [R] Reverse the direction of animation.
  • [P] Pause and restart animation. Press twice quickly while paused to step by a single frame.

Click here to run the program in a new tab/window

As an aside, I was astonished to discover that Safari (even the old PC version that hasn’t been updated for years) is blindingly fast at drawing these spirals, running many times faster than Firefox (which comes a distant second), followed by Chrome and Opera running even more slowly, and Internet Explorer limping along in the rear (well, actually I expected that…) What is Apple doing so well here? Is it using super-efficient math routines? Does it access the canvas more efficiently? I’d love to know – even Safari on my Macbook Air runs faster than Chrome or Firefox on my 16GB, 64-bit, i7-3770 PC!

Anyway, following is the source for the complete program (as it stood on June 1st 2014), so you can view it now if you are interested:

<!DOCTYPE html>
<meta charset='UTF-8'>
<html><body>

<canvas id='canvas1' width='600' height='600'></canvas>
<canvas id='canvas2' width='600' height='600'></canvas>

<script>
// Global Objects

canvas1  = document.getElementById('canvas1') // Get canvases
canvas2  = document.getElementById('canvas2')
context1 = canvas1.getContext('2d')           // Create contexts
context2 = canvas2.getContext('2d')

C = 0                                         // Frame counter
P = getprimes(1500000)                        // Pre-populate primes array P[]
Q = []                                        // Array of random numbers
R = 0.0002                                    // Spiral radius increment
S = 1                                         // Resume direction after pause
T = 1                                         // Direction of animation
U = 0                                         // For tracking prime groups
V = 1                                         // Pixel width and height
W = 0                                         // Animation delay
X = 300                                       // Center of spiral...
Y = 300                                       // ...X & Y coordinates
Z = 0                                         // For tracking prime pairs

for (var f = 0, j = 0 ; j < P.length ; ++j)   // Populate random array Q[]
  Q.push(f += Math.floor(Math.random() * 27.2))

spiral()                                      // Start animation

// Functions

function spiral()                             // Draw the current spiral frame
{
  canvas1.width += 0                          // Clear canvas 1
  canvas2.width += 0                          // Clear canvas 2
  var d          = (Math.PI * 100000) / P[C]  // Gap between plots
  var n          = 0                          // Index counter into P[] and Q[] arrays

  context1.font  =                            // Provide status info
  context2.font  = "11pt 'Times New Roman'"
  context1.fillText('Primes: (π × 100000) / ' + P[C] + ' =', 0, 10)
  context2.fillText('Random Numbers', 0, 10)
  context1.fillText(d, 0, 30)

  if (Z == 0 && U == 0) context1.fillText('All primes',      0, 50)
  else if       (U > 0) context1.fillText('Groups of '  + U, 0, 50)
  else                  context1.fillText('Distance: '  + Z, 0, 50)

  for (n = 0 ; n < P.length ; ++n)            // Draw both spirals
  {
    var g = P[n] * d                          // Distance around spiral 1...
    var h = P[n] * R                          // ...and out from the middle
    var i = Q[n] * d                          // Distance around spiral 2...
    var j = Q[n] * R                          // ...and out from the middle
    var f = false                             // True if a point is to be plotted

    if (Z == 0 && U == 0) f = true            // All primes
    else if (U > 0)                           // Groups of primes
    {
      f = true                                // Assume plot is required

      for (var k = 0 ; k < U ; ++k)
        if (P[n - k] - P[(n - k) - 1] > 4)
          f = false                           // Group not found - so no plot
    }
    else if (P[n] - P[n-1] == Z) f = true     // Pairs of primes

    if (f) context1.fillRect(X + Math.floor(Math.sin(g) * h),
                             Y + Math.floor(Math.cos(g) * h), V, V)

    context2.fillRect(X + Math.floor(Math.sin(i) * j),
                      Y + Math.floor(Math.cos(i) * j), 1, 1)
  }

  C += T                                      // Increment/decrement index into arrays

  if (C < P.length && C > -1)
    setTimeout(spiral, 4 + W * 333)           // Finished, so start next frame

  if (C < 1)              T =  1              // reverse animation direction if needed
  else if (C >= P.length) T = -1
}

function getprimes(a)                         // Return array of primes up to number a
{
  var p = [], n = 0
  while (n < a) if (isprime(++n)) p.push(n)
  return p
}

function isprime(n)                           // Check a number for primality
{
  for (var i = 2 ; i <= Math.sqrt(n) ; i += 1)
    if (n % i == 0) return false
  return true
}

document.addEventListener('keydown', function(e) // Listen to keyboard
{
  var f = false
  e     = e || window.event

  var keyChar = String.fromCharCode(e.keyCode).toLowerCase()

  if (e.ctrlKey)
  {
    switch(keyChar)                           // Select primes by group
    {
      case '1': f = true; U = 0; Z = 0; break // All primes
      case '2': f = true; U = 0; Z = 2; break // Distance: 2
      case '3': f = true; U = 3; Z = 0; break // Groups of 3
      case '4': f = true; U = 4; Z = 0; break // Groups of 4
      case '5': f = true; U = 5; Z = 0; break // Groups of 5
      case '0': case '6': case '7': case '8':  case '9': f = true
    }

    if (f) return canceldefault(e)
  }

  if (e.altKey)
  {
    switch(keyChar)                           // Select Speed of Animation
    {
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        f = true; W = parseInt(keyChar); break
    }

    if (f) return canceldefault(e)
  }

  if (e.shiftKey)
  {
    switch(keyChar)                           // Select pixel size
    {
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        f = true; V = parseInt(keyChar) + 1; break
    }

    if (f) return canceldefault(e)
  }

  switch(keyChar)                             // Select prime pairs
  {
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
      f = true; Z = parseInt(keyChar) * 2; U = 0; break

    case 'r': f = true; T = -T; break         // Reverse direction
    case 'p': f = true                        // Pause and restart

              if (T != 0) { S = T; T = 0 }
              else        {        T = S }
  }

  if (f) return canceldefault(e)
})

function canceldefault(e)
{
  if (e.stopPropagation) e.stopPropagation()
  if (e.preventDefault)  e.preventDefault()
  return e.returnValue = !(e.cancelBubble = true)
}
</script></body></html>
Posted in Articles, Features, Observations | Leave a comment

A First Hypothesis on My “Nixon” Prime Spirals

A 'Nixon' SpiralSomewhere around 200BC a Greek mathematician called Eratosthenes described a sieve method that could be used to generate prime numbers. For low prime numbers it’s not too hard to tell whether a number is prime by testing it for having integer factors. But as you move on to large and larger numbers this takes more and more time, so methods based on this sieve are often used to gain speed. It works like this:

Write down all the numbers you want to test for primality. Once you have this list locate the first prime number after 1 and erase every multiple of it. This will remove 4, 6, 8, and all other even numbers, leaving 2. Having done this locate the next unerased number, which will be 5. So now count along your list and erase every multiple of it such as 10, 15, 20, and so on. Now move onto the next number, which will be 7, and delete all multiples of that (14, 21, 28, and so on), and the next unerased number will be 11.

Sieve of EratostheneseYou see what’s happening here? One by one we are discovering the prime numbers as we move up the number list. And at the same time, we’re are quickly removing rafts of non-prime numbers throughout the rest of the list, consequently discovering primes without a single division operation in sight.
Now, imagine that you write this list of numbers in a spiral and then draw lines instead of erasing numbers when you conduct each sieve operation. Depending on how closely together you wrote the numbers, you’ll see spirals radiating out in a variety of different curves.

Considering the prime spirals I’ve been creating recently, in which only prime numbers (or pairs, triplets or other combinations of primes) are plotted, you can imagine the primes not plotted as being drawn using the sieve process in white lines.  And this is what I hypothesize I am finding. These spirals actually bring out the sieve spirals, resulting in the patterns found.

A Prime Spiral with radial 'spokes'Of course, when the correct spacing values are used the spirals form straight radial lines, and that’s why the images in my previous article look more like bicycle wheels than spirals – I used multiples of 360 in the distance to straighten them up. So, to remove this straightening effect I removed the 360 and replaced it with prime numbers and found spirals going in both clockwise and counterclockwise directions (at the same time), and with different curvatures too.

To get a better understanding of what is happening I then wrote the code to animate all distances between potential plot points from pπ to π ÷ 2, π ÷ 3, π ÷ 5, π ÷ 7,  and so on (diving pi only by prime numbers to remove the possibility of integer divisors creating artificial patterns). What happens when π is used is you get a straight line because the distance between all potential plots is a semi-circle, so the spiral is a single line going straight out. as you increase the divisor, more ‘spokes’ appear as more potential plot locations become available, until you get into divisors of a few hundred, when the spokes are so close to each other patterns can start to be revealed.

Interestingly, if this process continues, the final result will be a single straight line again. But only when it reaches π/infinity. So in the programs below, once the divisor gets into the several thousands, you’ll see a new spiral begin to emerge and the prime patterns will be harder to see, This is because the distance between potential plots is so close that plot points are overlapping each other, resulting in just a spiral line (the one that will end up straight at infinity).

So following is what happens when you use (for example), the prime number 2143 as the divisor for calculating the plotting distance gap:

A 'Nixon' Spiral

Here we see another benefit to not making the ‘spokes’ straight, because now it’s possible to determine the directions in which they curve. Anyway, for comparison (and to try to check that all this isn’t hogwash and caused by simple interference patterns or something), here’s the same value used but with random numbers ending in 1, 3, 7, or 9 being plotted, rather than prime numbers – not much to see here (thankfully!):

A Random Spiral

Here is a combined program you can try for yourself to create prime and random ‘Nixon’ Spiral animations. Note that things are a little boring for the first few dozen frames, but bear with the animations, as patterns very soon start to emerge – there are also a number of keyboard options available for controlling the animation:

By the way, after viewing these animations over and over, I’m now fairly sure that above a rough value of around 1700 or thereabouts, the interference effects (unexpected white ‘spokes’) of non-prime plot distance gaps is vastly reduced. So here’s a version of the Prime Spiral Animation program that counts in linearly decreasing gap sizes, starting with π ÷ 1700 (then π ÷ 1701, π ÷ 1702, and so on), rather than by the next smallest prime number fraction of π ÷ n. When you watch this animation you can see left-swirling spirals turn into radial spokes in the following frame, and then right-swirling spirals in the next. Just like turning a radio dial, I think sieves gets tuned in one (or many) at a time until they show as straight spokes at maximum ‘tuning’ (and often many different sieves can be be seen in action at the same time in a frame):

Here’s an example frame from this program exhibiting these spokes (the frames immediately prior and after this display as spiral arms):

A Spoked 'Nixon' Spiral

So, what do you think? Is it the Sieve of Eratosthenes we’re seeing here. And, if so, does it have implications for understanding more about prime numbers, or even finding them more easily, for example?

Posted in Articles, Features, Observations | 2 Comments