Much like this site, my current project has reputation and in the script that I'm working on I need to calculate the ratio between two users' reputations.
$attacker->ratio = $defender->rep / $attacker->rep;
$defender->ratio = $attacker->rep / $defender->rep;
In doing so I may occasionally end up with the divisor's reputation being 0, which sucks!
Obviously I can add a couple of checks, but I was wondering if a prettier solution hasn't been invented, something like @
infront, but I know that's not a good idea..
Arguably the cleanest (mathematically) method to avoid divide by zero errors is to multiply quantities, rather than dividing one by the other. This method, while adding no overheads to the simulation, would require the reformulation of some equations to be adequately implemented.
We can avoid this error message using the following three methods: Using NULLIF() function. Using CASE statement. Using SET ARITHABORT OFF.
php //PHP program to demonstrate the //Divide By Zero Exception using exception handling. try { $A = 10; $B = 0; if ($B == 0) throw new Exception("Divide by Zero exception occurred"); $C = $A / $B; printf("Value of C: %d<br>", $C); } catch(Exception $e) { printf("Exception: %s", $e->getMessage()); } ?>
So, how do you avoid division by zero in SAS? You can avoid division by zero in two ways. First, you can use an IF-ELSE Statement. Second, you can use the DIVIDE function.
Assuming positive numbers are valid then ensure the lowest divisor value will be 1.
$defender->ratio = $attacker->rep / max($defender->rep, 1);
// --------------------------------------------
suggested code by someone else,
@php_nub_qq suggested alternate code...
In today's php
$defender->ratio = $attacker->rep / ($defender->rep ?? 1);
Alas, this code provided by @php_nub_qq does not work in PHP 7.4 ;-( see @OceanBt in the comments... I thank them for the correction! :)
so, Here I am maintaining code that I never was interested in. And now, is shown to be PHP version specific! Here is the correction...
$y = 100/($x ?: 1);
Why am I doing this?
I don't mind doing this maintenance of the code of someone else! This is the real world! We have to do this. I posted it because:
I really am trying to help programmers to learn.
// My thoughts about the 'improvement' to what I posted...
imo, that suggestion of yours isn't the same as my approach! I specifically used 'max' as it forces a limit on a range of numbers. You can nest the 'min' and 'max' functions also to force a limited range.
Your method is a 'selection' and not why I did the answer I did. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With