PDA

View Full Version : Visualizing Prime Numbers with MoGraph?


Newstream
10-09-2007, 09:08 PM
Sorry for the oddball question but...
Is there some simple method (either via xpresso or coffee) to identify a number in a sequence as a prime number thereby triggering a boolean operation?

Its for a mathematical visualization project..
For example: I'd like to put a whole bunch of white cubes into a cloner object in linear mode but have cubes 5, 7, 11 etc. (and all the other prime numbered ones upwards in the series) be colored red or in some way stand out visually.

Any ideas on how to pull this off?
Tips and hints greatly appreciated.

Cheers / Alex

Per-Anders
10-09-2007, 09:17 PM
you could do it the slow way using coffee and a mograph selection tag. get the index, calculate using coffee whether it's a prime number, if it is, then select that index, otherwise ignore.

JamesMK
10-09-2007, 10:07 PM
Something like the attached file (probably requires 10.5... can't remember when the MoGraph selection tag was introduced).

Anyways, starts with 0 (zero) at bottom left cube... Should continue to work properly if X and Y clone counts are increased. Do not use Z-clones.

Newstream
10-09-2007, 10:47 PM
Thanks James! (hygglo) and Per
I really appreciate this. :thumbsup:

I'll be receiving 10,5 in the mail tomorrow so I'll be checking out your file when I get the opportunity.

My Coffee skills are rudimentary at best and examining existing setups like this is very helpful in figuring stuff out.

Cheers / Alex

ChrisCousins
10-12-2007, 06:36 PM
I like it! Very impressive that this works as well as it does, just the sort of thing to get mathematicians all excited! I added the z-axis, turned the numbers up really high, then I could have sworn I saw the face of God when I looked at it from a certain angle...

http://homepage.mac.com/chrissyboy/.Pictures/dump/god.jpg

Newstream
10-12-2007, 09:52 PM
Nice one Chris.
Well, mathematicians have for centuries been trying to decipher and figure out a pattern to the seemingly unpredictable occurrence of prime numbers. Our brains are comfortable with viewing numbers in neatly stacked arrays and (x,y) charts which may be one of the reasons why identifying a pattern to prime numbers is so elusive. If there is one, maybe it doesn't conform to an array or decimaly organized sequence of numbers but something more organic and naturally occurring like a spiral / snail / galaxy? With MoGraph, you have the freedom to organize numbers into varying shapes, patterns & sequences which make various numerical scenarios easier to grasp visually.

Thanks again to James for the excellent base file.

Cheers / Alex

http://www.badtastic.com/misc/primenum.gif

JamesMK
10-12-2007, 10:59 PM
You're welcome.

And yep, it is indeed tempting to try to find that elusive, magical representation in which the primes would suddenly turn out to exhibit some predictable pattern or symmetry, solve the "fast prime factorization" enigma and get filthy rich by blackmailing the RSA :D

I have a feeling that the answer has something to do with 14-dimensional Pretzels deformed by geodesic squirrels.

It's really difficult to visualize.



.

Per-Anders
10-12-2007, 11:46 PM
the only interesting pattern i can discern is that on multiples of 6 in a 2d grid you get clear vertical lines and columns of prime numbers after the first 10 with absolutely no numbers off of these lines. technically if you were certain of this fact you could then use this to optimize the algorithm substantially in combination with a lookup table (at least a factor of 5x as the largets gap between columns is 5). the potential is there to find a pattern within these columns, of course I'm sure this is all common knowledge to those interested in prime numbers, never really followed it much myself.

Just to add, the best pattern visible is with 54 columns, this gives a perpetually even column system that is gap, prime, gap, gap, gap, prime repeated accross the board. Using this knowledge we culd speed up the calculation of prime numbers by a factor of 2/3 by simply skipping those columns and resetting the lookup on each base 54.

Per-Anders
10-13-2007, 12:18 AM
So just to slightly optimize James code using this (though as the COFFEE parser is pretty fast this actually is a very maginal part of the overall scene speed) the code could be rewritten as follows, thus speeding things up considerably in the higher prime calculations :

is_prime(val)
{
var d = 0, fld = float(d);
for (d = floor(val/2.0); d > 1; --d)
{
fld = val/d;
if(fld == floor(fld)) return 0;
}
return 1;
}

main()
{
// special case for 1,2 and 3:
if (Input1 < 4)
{
if (Input1 == 1) Output1 = 0;
else Output1 = 1;
return;
}

//There are no primes on base 6 at 0,2,3,4
var mod = Modulo(Input1, 6);
if (mod == 5) mod = 1;
if (mod != 1)
{
Output1 = 0;
return;
}

// test the rest arithmetically:
Output1 = is_prime(Input1);
}

Newstream
10-13-2007, 12:21 AM
Yes, 6 is a really practical number. It gets along nicely with all the other numbers - It divides cleanly, without any fuss with 2,3 6,1 and as you say does discern some semblance of pattern. The xpresso setup in James's example is straight forward, its only the coffee part that's got me. If I wanted to add an additional Shader Effector with a user defined color of blue to highlight all 6's (6-12-18-24 etc) via an additional MG selection tag, what little line of coffee would I need to add to trigger a ON-bool for the second blue tag?

Would this work?

{
// special case for 6:
if(Input1==6)
{
Output1=1;
}
else if(Input1==1)
{
Output1=0;
}


By the way, is it possible to generate a helix in C4D that looks like this? Can't get the Helix spline in C4D to resemble this more natural variant.

http://img19.imageshack.us/img19/7016/goldenspiralic0.jpg

Cheers / Alex

Per-Anders
10-13-2007, 12:27 AM
It should be mentioned that there are other patterns within the figures, for instance within the columns, there are apparently never more than 4 primes in a row, thus we could make some assumptions and skip that, or we could continue calculating till we hit a situation where that occurs, however given current patterns up to the 60th vertical row I would say it's a safe assumption to make that you only get maximum sequence of 4, the gaps themselves however can be of any length, but appear to peak at around 9. So we'd be able to get a little bit more of a speedup using these assumptions.

http://www.peranders.com/general/primecolumns.png

Per-Anders
10-13-2007, 12:33 AM
Yes, 6 is a really practical number. It gets along nicely with all the other numbers - It divides cleanly, without any fuss with 2,3 6,1 and as you say does discern some semblance of pattern. The xpresso setup in James's example is straight forward, its only the coffee part that's got me. If I wanted to add an additional Shader Effector with a user defined color of blue to highlight all 6's (6-12-18-24 etc) via an additional MG selection tag, what little line of coffee would I need to add to trigger a ON-bool for the second blue tag?

Would this work?

{
// special case for 6:
if(Input1==6)
{
Output1=1;
}
else if(Input1==1)
{
Output1=0;
}

Nope, you need to use a Modulo like function, the simplest way for those with some classical background is to do it like this:

if (Modulo(Input1, 6) == 0) Output1 = 1;
else Output1 = 0;

The faster way for the machine though is to do it like this:

var div = Input1/6.0;
if (div == floor(div)) Output1 = 1;
else Output1 = 0;

By the way, is it possible to generate a helix in C4D that looks like this? Can't get the Helix spline in C4D to resemble this more natural variant.

http://img19.imageshack.us/img19/7016/goldenspiralic0.jpg

Cheers / Alex
There's no inbuilt golden ratio afaik, however you could probably put the function into a formula spline for it. If you use the per step mode for the linear mode of a matrix object and then used a tracer in connect mode on that you would be able to get a similar looking spline (but not accurate to the golden ratio).

Newstream
10-13-2007, 01:01 AM
Thanks a lot for this Per.
I need to hit the sack but tomorrow I'll continue with this + my machine is rendering stuff overnight.

Its great to see the prime numbers laid out onto a large "map" as dots (totally visual!) but it would be very interesting to see their positions relative to the repeating sequence or grid of 6 (or on a spiral) and to see if one can determine any relationships or draw conclusions as a basis for rules about the behavior of prime numbers..Its a foggy subject, but thats why MoGraph is so flexible here and useful at "showing" something which would otherwise be difficult or too abstract to describe to someone using unintelligible equations on a blackboard.

Cheers / Alex

Per-Anders
10-13-2007, 01:27 AM
Well the grid iposted does show the pattern against 6, in this case against 54 as it's the most recognizeable pattern, but by subtractive synthesis we can ccontinue to remove columns using base 6. Basically all we would do is increate by 6 for columns and check out the visible patterns, via that we can remove whole columns (i.e. very many numbers that should not be tested) in different bases.

e.g. lets shift it up to 120 accross, still vertical columns, but looks a little more chaotic yes?
http://www.peranders.com/general/primecolumns2.png
However, not so! The patternis repeating again.

This time it's a little more complex, so i'll write it as numbers of spaces between columns that potentially can contain prime numbers.

1, p, 5, p, 3, p, 1, p, 3, p, 1, p, 3, p, 5

Now that's a repeating and mirrored pattern that we can use once again to subtract columns from our calculations thus reducing the numbe of calulcations that are needed :)

If we were to remove the whole numbers form this to contactenate the actual pattern becomes

p, 2, p, 1, p, p, 1, p, p, 1, p, 2, p
or in binary fashion 100101101101001, nice pattern, nice and symetrical. Goes nicely with our existing 101 based existing pattern from 54 columns.

So we can basically do the same thing and do a heuristic search for prime numbers based on this stuff. All we do is take at increment of 6, find the pattern if one exists, subtract the columns on a table based on the base of the length of the pattern. I'm not saying that eventually this would cause a prime subtractive synthesis engine, but it would be a good way to speed up prime calulcations without having to test and check every single number out there.

I assume that other people have already found this stuff out and it's part of all the math research surrounding prime numbers (though come to think of it i've never seen it explained like this in these terms, so you never know we might have stumbled on a "trade secret", but i highly doubt it). I just find it odd that people say there are no patterns to prime numbers (apart from them all being odd asside from 2), in a few minutes of exploration of them I've found numerous cohesive patterns and rules based on their representation of course.
:shrug:

ChrisCousins
10-13-2007, 02:15 AM
is_prime(val)
{
var d = 0, fld = float(d);
for (d = floor(val/2.0); d > 1; --d)
{
fld = val/d;
if(fld == floor(fld)) return 0;
}
return 1;
}
[/QUOTE]

Not a coffee writer by any means, but two things occur here
1) wouldn't it be simpler to start with low numbers ie when checking if 29887 is a prime, the best place to start is to ask is it divisible by 3, rather than starting high?
2) would it be possible to skip all evens other than 2?

Apologies if I've misread the above code.

There's all sorts of amusing prime trivia - apparently any number can be written as the sum of two primes. Prove this (or disprove it ;) ) and win your first Nobel prize :D

C

Per-Anders
10-13-2007, 03:38 AM
Oh yes, it's not very good as a loop, it's certainly slower, part of an earlier experiement I forgot to change. Typically though you should set the divide to a variable as this is evaluated for every single loop call, typically also predecrement/increment is faster than post and comparing to a static is faster than to a variable, fastest of all to 0 which is why i have a habit if decrementing always. Of course for COFFEE this makes little to no difference (apart form divides still being slower than multiply addition).

Here's a little bit of improved code that also factors in two column filters and a prime filter (a slightly quicker "predictive" way of filtering out non primes than doing the full division on every single number, although not totally optimal it can reduce the total number of prime checks substantially if you then go on to the next stage and remove the full "is_prime" routine at the top after a certain prime has been achieved).


is_prime(val)
{
var d = 0, fld,
max = floor(val*0.5);
for (d = 3; d <= max; d += 2)
{
fld = val/d;
if (fld == floor(fld)) return FALSE;
}
return TRUE;
}

var prime_filter, prime_filter_count, max_prime_count;

run_test(val)
{
// special case for 1,2 and 3:
if (val < 6)
{
if (val == 1 || val == 4) return 0;
else return 1;
return 1;
}

if (!(val&1)) return 2;
val = float(val);

//There are no primes on base 6 at 0,2,3,4
var mod = Modulo(val, 6);
if (mod == 3) return 2;
mod = Modulo(val, 15);
if (mod == 5 || mod == 10) return 2;

//Filter out numbers based on prime division
//This reduces the number of divisions checks required
//However as there are so many prime numbers we can run out of memory
//When calculating large primes, so we limit to just the first 1000
///Uncomment this method to try out a more predictive method
/*if (prime_filter)
{
var i = 0;
for (i = 0; i < prime_filter_count ; ++i)
{
mod = val/prime_filter[i];
if (mod == floor(mod)) return 2;
}
}
return 1;
*/

// test the rest arithmetically:
return is_prime(val);
}

main()
{
prime = FALSE;
filter = FALSE;

//Only allocate the once
if (!prime_filter)
{
max_prime_count = 1000; //maximum prime filters
prime_filter = new(array, max_prime_count);
}

switch (run_test(num))
{
case 1:
{
prime = TRUE;
if (num == 0) prime_filter_count = 0;
if (num > 1 && prime_filter_count < max_prime_count) prime_filter[prime_filter_count++] = num;
} break;
case 2: filter = TRUE; break;
default: break;
}
}


To use this, I modified the COFFEE node to have a single integer input and two bool outputs, named the input "num" and the outputs "prime" and "filter", fitler goes to a second selectino tag that allows me to see what indeces i'm filtering off, and prime goes to the selection on the prime value. This code is slower with smaller numbers of primes, but faster with higher numbers. You can manually adjust the prime filter maximum size.

Per-Anders
10-13-2007, 04:30 AM
Just to point out why i left both methods in the code there, that way you can see the accuracy of the filter system (by uncommenting the prime fitler, but leaving the return 1; lilne commented out). you'll see that it's a nice simple optimization, where e.g. only a max prime count of 10 will keep it accurate nearly to checks in the 1000 range, so at that end only 10 checks compared to 250. As you'd expect higher prime storage leaves you with a somewhat logarithmic increase in accuracy for substantially less computation (but an ever increasing amount of memory).

here's the version with it just using the prime filter (faster when dealing with larger numbers) and a dynamically resizing array.


var prime_filter, prime_filter_count, accuracy_factor;

is_prime(val)
{
// special case for 1,2 and 3:
if (val < 6)
{
if (val == 1 || val == 4) return FALSE;
return TRUE;
}

if (!(val&1)) return FALSE;
val = float(val);
var i = 0, mod;
for (i = 0; i < prime_filter_count ; ++i)
{
mod = val / prime_filter[i];
if (mod == floor(mod)) return FALSE;
}

return TRUE;
}

main()
{
if (!prime_filter)
{
prime_filter = new(array, 128);
prime_filter_count = 0;

accuracy_factor = 100;//enough for a *lot* of clones, have this at around 1/100th of your clone count
//or simply raise it to a super high value to allow full accuracy (but it will be slower)
}

Output1 = is_prime(Input1);

if (Output1)
{
if (!Input1) prime_filter_count = 0;
if (Input1 > 2 && prime_filter_count < accuracy_factor) //accuracy factor
{
if (prime_filter_count >= sizeof(prime_filter))
{
//resize the array
var arr = new(array, prime_filter_count + 128);
//COFFEE doesn't appear to have a resize/memcpy function for non byte arrays
var i;
for (i = prime_filter_count - 1; i >= 0; --i)
{
arr[i] = prime_filter[i];
}
prime_filter = arr;
gc(); //garbage collection
}
prime_filter[prime_filter_count++] = Input1;
}
}
}

vbvcvj
10-13-2007, 05:11 AM
With dynamic selection, Mograph is getting better and better, which will make it perfect is a true L-system.

Per-Anders
10-13-2007, 05:47 AM
You can construct a basic l-system with it right now, just clone on clones, or if you want use linear matrices, the tracer in connect mode and the cloner (cloning matrices on the tracer) to build branching structures.

ChrisCousins
10-13-2007, 09:36 AM
Really interesting, I never realised how much COFFEE looked like javascript/actionscript, which I know fairly well. Not so daunting after all.

Cheers -Chris

JamesMK
10-13-2007, 09:43 AM
Really interesting, I never realised how much COFFEE looked like javascript/actionscript
Very true. EDIT: You'll notice some differences later on though, compared to JS, as the typical JavaScript stuff is more biased towards procedural approaches, whereas coffee and the SDK is heavily OOP oriented. So, instead of accessing arrays in the standard web document DOM for instance, you're more likely to be passing around pointers and object references instead when dealing with Cinema documents. /edit

To dig deeper into it, I recommend checking out the various classes of the COFFEE SDK, which you can download from www.plugincafe.com. Unfortunately it's not really synced with the current state of the C++ API, so you're basically limited to what could be done in R9.5, but that's on the other hand quite a lot already.

vbvcvj
10-14-2007, 09:05 AM
Hi, Per, is there a way to use a texture map to generate a mograph selecton ?

Per-Anders
10-14-2007, 06:17 PM
Not without an Xpresso node that can sample a texture (I believe that DiTools has something for this), you can sample bitmaps though in Xpresso without a plugin and use that. And of course you can always not use selections at all, but simply use the texture effector to affect Mograph particles using a texture (that includes offsetting the weight value so that the texture will drive other effectors, a similar effect to selections but a little more powerful).

Newstream
10-14-2007, 07:26 PM
Sorry for the radio silence..
Been digesting / mulling..
In the meantime, I stand corrected:
http://www-groups.dcs.st-and.ac.uk/~history/HistTopics/Prime_numbers.html
Its worth mentioning here that the historic characters mentioned in this piece obviously didn't have something like mograph to fool around with and probably did things the old fashioned (hardcore) way using either clay tablets or blackboards.

Judging by the following: http://www.fermi.franken.de/wschildbach/primes.html its also obvious the we weren't first in visualizing primes into image maps to discern repeatable patterns. *sigh* ...was fun though.. :shrug:

/ Alex

CGTalk Moderation
10-14-2007, 07:26 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.