Created
October 6, 2013 16:55
-
-
Save kafene/6856361 to your computer and use it in GitHub Desktop.
Repulsion-Force (Colomb's Law)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env php | |
| <?php | |
| # From: http://www.reddit.com/r/dailyprogrammer/comments/1ml669/091713_challenge_138_easy_repulsionforce/ | |
| function calculate_repulsion_force($mass1, $mass2, $distance) { | |
| $divisor = bcmul($mass1, $mass2); | |
| $dividend = bcpow($distance, 2); | |
| return bcdiv($divisor, $dividend); | |
| } | |
| function calculate_distance($x1, $y1, $x2, $y2) { | |
| # sqrt((x1 - x2)^2 + (y1 - y2)^2) | |
| $dx = bcsub($x1, $x2); # x1 - x2 | |
| $dy = bcsub($y1, $y2); # y1 - y2 | |
| $x2 = bcpow($dx, '2'); # dx ^ 2 | |
| $y2 = bcpow($dy, '2'); # dy ^ 2 | |
| $sum = bcadd($x2, $y2); # x2 + y2 | |
| return bcsqrt($sum); | |
| } | |
| function get_input($prompt) { | |
| $are_numeric = function () { | |
| # If the array is empty, all values were numeric, returns true. | |
| return !array_filter(func_get_args(), function ($n) { | |
| return !is_numeric($n); | |
| }); | |
| }; | |
| # I read these as strings instead of floats | |
| # so they can be larger than the max float value. | |
| print $prompt; | |
| $count = fscanf(STDIN, "%s %s %s", $mass, $posx, $posy); | |
| if (3 !== $count || !$are_numeric($mass, $posx, $posy)) { | |
| print "Incorrect input format.\n"; | |
| return get_input($prompt); | |
| } | |
| return [$mass, $posx, $posy]; | |
| } | |
| # Set bcmath precision scale to 5 | |
| bcscale(5); | |
| list($mass1, $x1, $y1) = get_input("Please enter the first particle as [mass] [pos-x] [pos-y]: "); | |
| list($mass2, $x2, $y2) = get_input("Please enter the second particle as [mass] [pos-x] [pos-y]: "); | |
| $distance = calculate_distance($x1, $y1, $x2, $y2); | |
| if ($distance == '0') { | |
| exit("The distance between the given particles is zero.\n"); | |
| } | |
| $force = calculate_repulsion_force($mass1, $mass2, $distance); | |
| print "Calculated repulsion force: $force\n"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment