http://www.perlmonks.org?node_id=42827

You really, really, don't want to use this, but it's fun. Unless of course you get paid by the hour and feel the need to add a subtle new bug to your code.

::Analytical will decay as though it is a collection of a large number of particles, so could represent the rate of emmissions from a sample say. ::Discreet will decay as though it is a single particle, and obeys the 'if you look you alter things' principle.

::Analytical was written by someone else, but had a bug which is fixed in this version, ::Discreet is all mine.

my $half_life = 5; # seconds my $foo; tie $foo, 'Radioactive::Decay::Analytical', $half_life; $foo = 100; for (1..10) {print $foo,"\n"; sleep(2)} tie $foo, 'Radioactive::Decay::Discreet', $half_life; $foo = 100; for (1..10) {print $foo,"\n"; sleep(2)} package Radioactive::Decay::Analytical; sub TIESCALAR { bless [0,log(2)/$_[1],0], $_[0]; } sub STORE { $_[0]->[2] = time; $_[0]->[0] = $_[1] } sub FETCH { $_[0]->[0] * exp(-$_[0]->[1] * (time - $_[0]->[2])) } package Radioactive::Decay::Discreet; sub TIESCALAR { bless [0,log(2)/$_[1],0], $_[0]} sub STORE {$_[0]->[2] = time; $_[0]->[0] = $_[1]} sub FETCH { if (rand() < (1-exp(-$_[0]->[1] * (time-$_[0]->[2])))) + {$_[0]->[0] = 0} else {$_[0]->[2] = time} $_[0]->[0];}

There are slight problems with this (the model departing from physical reality), in that the time resolution is very limited, if you want to avoid this you need to keep it running for a long time, increase the half life and check the particle less often...