in reply to Square Root algorithm
Hey, cool problem, nysus... I'll throw out my code, first. Be forewarned, though -- I'm nowhere near the pro you asked for.
#!/usr/bin/perl -w use strict; sub sqroot { my $maxdiff = 1e-18; my ($value, $num) = (1, shift @_); my $i = ''; # Added $num *= -1 and $i = 'i' if ($num < 0); # Added my $oldvalue = 0; while (abs($oldvalue - $value) > $maxdiff) { $oldvalue = $value; $value = $num / $value; $value = ($value + $oldvalue) / 2; } # return $value; # (old) return $value . $i; } my $num; do { print "Please enter a number: "; # changed from "positive number" chomp ($num = <STDIN>); # } until ($num =~ /^\d*[.\d]\d*$/); # (old regex) } until ($num =~ /^-?\d+\.?\d*$/); my $sqrt = sqroot $num; print "Square root of $num: $sqrt\n";
Now, for a few comments:
Once again, considering that optimial is a relative term, you're free to call my ideas ridiculous, if you like. :) Once again, though, cool problem... made me think a good bit. (I'll probably still be thinking about it tomorrow...)
Update: I just couldn't leave well enough alone. Above are modifications to the original script that allow processing of negative numbers, as well as an improved (?) regex. Also changed $maxdiff as per ariels' suggestion.
His Royal Cheeziness
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Square Root algorithm
by nysus (Parson) on Jun 25, 2001 at 11:37 UTC |