dbdiaz has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks! I havent done any trial-n-error type programming before and was wondering if anyone can point me to some useful resource regarding this.

For example, I have x1+x2+x3 = 10.33. I want to randomly generate 3 numbers -- x1, x2, x3 -- that will equate 10.33 (approximately of course!)

Thanks in advance!

Replies are listed 'Best First'.
Re: Trial and error problems in Perl
by Tanktalus (Canon) on Jan 23, 2007 at 00:03 UTC

    Like most programming, start with how you'd do it by hand. You might realise how many assumptions you've made, or maybe not, but your code can be written to follow the same method to get similar answers.

    For example, come up with a nice random number first (rand) ... but in what range? To what precision? Are negative values allowed? These will all impact the way to come up with the next random number (whose range will be determine by the original range, modified by the previous number). And, finally, the last number just is 10.33 minus the total of the other two numbers.

    My useful resource is usually "how would I do this by hand" - and I go from there. Good luck!

Re: Trial and error problems in Perl
by BrowserUk (Patriarch) on Jan 23, 2007 at 00:59 UTC

    Generate any three random numbers from any range; sum those numbers; multiply the base number by each of your 3 random numbers in turn and divide by their sum. Result three random numbers that add up to the base number:

    Perl> @rands = map{ rand 1000 } 1 .. 3;; Perl> $t += $_ for @rands;; Perl> ( $x1, $x2, $x3 ) = map{ 10.33 * $_ / $t } @rands;; Perl> print "$x1 + $x2 + $x3 = ", $x1 + $x2 + $x3;; 5.13264782081133 + 0.820661299314597 + 4.37669087987407 = 10.33

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      thanks a lot browserUk. you've put me on the right track to think about the problem i am solving.

      cheers!

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Trial and error problems in Perl
by Joost (Canon) on Jan 23, 2007 at 00:38 UTC
Re: Trial and error problems in Perl
by Fletch (Bishop) on Jan 23, 2007 at 00:36 UTC