>=
Why use the above and not just the greater than but with one number less.
For example:
> 8
Is the same as
>= 9
I know it's not a huge deal, but it just seems to serve no purpose to me.
FYI I'm still fairly beginner with PHP so I'm asking a lot of 'why's' at the moment
Let's use an example where you want to cover the left side of the equation being greater than or equal to data input by a user or coming from another variable (something where you don't actually have a hardcoded number).
Your options are $value >= $input or $value > ( $input - 1 )
Very often when writing software, you won't have a specific number in mind. Values change. Writing production software is more about logic than it is math.
How would you represent any number greater or equal to 1? If your logic was true, then $value > 0 would be enough, but if we are dealing with decimals, then 0.95 would be greater than 0 and this 0.95>0 would equate to TRUE while 0.95 >= 1 would equate to false.
You might then follow up your question with "What if we are only using integers and not decimals?". Then in that case mathematically you are correct in assuming that the logic would be the same in most situations (I say most because to say something is ALWAYS true in programming is a dangerous statement to make).
However, in practical terms, >= is more visual and clear to most, and if for some reason you had to change your code in the future to take decimals into account, your site would have a costly error.
Related
This question already has answers here:
PHP round half up doesn't work
(3 answers)
Closed 6 years ago.
Not sure if this is normal but personally, I think it is not giving me the right result. Lets look at this example
$a = 3.32475;
$b = round($a,2,PHP_ROUND_HALF_UP);
I was expecting 3.33 but instead I get 3.32. Am I missing something here? Is the rounding function only literally uses the 3rd decimal point value instead of the whole value, and then rounding it up?
What I was expecting was something like this:-
- 3.32475
- 3.3248
- 3.325
- 3.33
Am I doing something wrong here? is there a better way for me to get an accurate rounding base on the whole value rather than the 3rd decimal point?
Thanks.
It would round up to 3.33 anything >= 3.325. Your value is less than that, so it rounds down to 3.32.
As stated in the docs, PHP_ROUND_HALF_UP means:
Round val up to precision decimal places away from zero, when it is half way there. Making 1.5 into 2 and -1.5 into -2. [Emphasis added]
If you want to force it to "round" up, use ceil() instead of round():
$a = 3.32475;
$b = ceil($a * 100) / 100;
This finds the "ceiling" value of 332.475, i.e., 333, then divides that by 100 to give 3.33.
Also, be aware that rounding never actually works the way you described (rounding digits one at a time) unless you write a special routine to do that (and I can't think of any real-world reason you would want to do so).
I often have fields in my database which store "a number or infinite". Examples could be maxFileSize, maxUsers, etc. It shall be possible to set a maximum value or just don't restrict it at all.
I currently sometimes use null to indicate "infinite / no restriction" and sometimes use -1.
I was wondering if there is any reason to use the one or the other. For the record, I work with PHP / MySQL / Doctrine / Symfony, if that matters.
Edit:
I am not asking for opinions but for facts (as you see in the answers already given) related to the usage of -1 or null. These might include speed, query complexity, database size, and so on.
If you are going to use an integer to store a value and you want to store a really large value, then use 2,147,483,647. This is the largest value you can put in the field, so it is as close to infinity as the field allows.
There are issues with both -1 and NULL. For instance, perhaps the value has not been set yet. That seems like a much more reasonable use for NULL than to represent some arbitrary value. And using a special value requires complicated logic:
where users < maxusers or maxusers is null
where users < maxusers or maxusers = -1
This specialized logic makes the query harder to optimize. This is not an issue if you use the maximum value that can be stored in the field.
By the way, I don't often encounter this problem with numbers, but it is very common with dates. Often "end dates" in tables for slowly changing dimensions will be something like: '9999-01-01' or '4195-01-01'. These represent some arbitrary point far into the future. And, they are usually easier for optimization purposes than using NULL.
Just imho
null - is expected by any framework or query as empty or not defined value in many cases. but if you try to use -1 or anything else. some query functions SUM(), AVG() etc could be broken by this value.
So I see no reason to get bad habit. null is null and everybody knows that null can exists in table and means empty or not defined.
In case you will place -1 that means not empty and defined so for me that is absolutely opposite values.
Can you ask if we can use 1 instead 0, true instead false?
if your value is defined and not empty - you can use whatever you want.
and if your value is not defined and/or context is value is empy I would suggest use nothing that equal null.
You may also choose to use two fields in your database to achieve the result:
file_quota int NOT NULL DEFAULT 50000,
file_quote_is_limited boolean NOT NULL DEFAULT true
There are a couple of ways to store boolean values in MySQL which can of course impact database size depending on your scale compared to simply storing unlimited as NULL. However, there are some advantages of this technique:
Even if you do not document that NULL means unlimited, when seeing the mapping it is more clear what is meant. (Consider new developers, etc.)
It is impossible to find if (null == $obj->getFileQuota()) { or similar constructs in your code. Those snippets are generally smelly and not maintenance friendly.
Query complexity depends on what you are trying to achieve, but the two fields do not add unforeseen complexity. In fact, it makes it easier to understand what is happening:
where file_quota < 50000 or file_quota is null
vs.
where file_quota < 50000 or ! file_quota_is_limited (the negation depends on your chosen datatype to map booleans, but Doctrine should take care of that)
If you happen to have $usage = $usedFiles / $user->getFileQuota(); in your code, you can even prevent division by zero from occurring by constraining the database column appropriately.
You can further extend your logic to map even more states.
Having NULL mean "no limit" is perfectly reasonable here. Using an actual integer value is bound to cause problems.
"Magic numbers" like -1 have a way of starting out harmless enough but ending up relevant later, meaning you need a new, more magical number to replace that.
That makes it easy to define bounds where min and max may be NULL rather than using some arbitrarily large or small value.
I have a little problem with round() in php.
I don't know, if I really make it correct.
(it is an order system)
$amount can be decimal 14,8
$price can be decimal 10,5 (in the database)
I am using the following rounding at this moment
The $price is for one $amount
function round_amount($amount) {
return (float) round($amount, 8);
}
function round_price($amount) {
return (float) round($amount, 5);
}
//if some one have more decimal chars like 10.000000009
round_amount(10.000000009); //will be 10.00000001
//if some one have more decimal chars like 10.000009
round_price(10.000009); //will be 10.00001
//also this is possible
round_price(round_amount(10.000000009)*round_price(10.000009))
Is this way correct to use round?
Some user are using more than 16 decimals.
I am deducting / adding the results in the user database.
But I see, that some user have about 5-10 cents too much!
Is the only way to resolve this, to allow ONLY 8 and 5 decimals?
And warn the user, if he tries to use more?
But than I will get an problem with the round_cur(round_amount(10.000000009)*round_cur(10.000009))
I hope some one understand what I am meaning, or can tell me, if my way to round is correct.
$amount = 10.12398413498579889173459873;
$price = 5.1938457198347695;
echo round_cur(round_amount($amount)*round_cur($price))."<br />";
echo round_cur($amount*$price);
//returns
//52.58245
//52.58241
Interesting!
Why not keep the actual value from the database cached and then have a separate variable for display. In that way all of the calculations can be done on the cached, correct, value while maintaining a clean UI. Just make sure to update the displayed variable each time the cached variable is updated.
Also, always apply math before doing any rounding. Multiplying two exact numbers is much more accurate than multiplying two rounded numbers. This applies for every operation in mathematics. So add, subtract, divide, multiply and then round, but never use that rounded number for another formula. Use the previous exact number.
I think you way is correct, but depend on your situation as you mentioned, those two formulas return different values and you are the one as the manager of the project which system is better for you (you should think about what is best for you and what is best for user and make up your mind and see if you choose either, what would be the trade of) and for this situation i recommend the first methid
round_price(round_amount(x)*round_price(y))
And for your problem a good notice or warning should do it. Give an example for user.
I have a tricky question that I've looked into a couple of times without figuring it out.
Some backstory: I am making a textbased RPG-game where players fight against animals/monsters etc. It works like any other game where you hit a number of hitpoints on each other every round.
The problem: I am using the random-function in php to generate the final value of the hit, depending on levels, armor and such. But I'd like the higher values (like the max hit) to appear less often than the lower values.
This is an example-graph:
How can I reproduce something like this using PHP and the rand-function? When typing rand(1,100) every number has an equal chance of being picked.
My idea is this: Make a 2nd degree (or quadratic function) and use the random number (x) to do the calculation.
Would this work like I want?
The question is a bit tricky, please let me know if you'd like more information and details.
Please, look at this beatiful article:
http://www.redblobgames.com/articles/probability/damage-rolls.html
There are interactive diagrams considering dice rolling and percentage of results.
This should be very usefull for you.
Pay attention to this kind of rolling random number:
roll1 = rollDice(2, 12);
roll2 = rollDice(2, 12);
damage = min(roll1, roll2);
This should give you what you look for.
OK, here's my idea :
Let's say you've got an array of elements (a,b,c,d) and you won't to randomly pick one of them. Doing a rand(1,4) to get the random element index, would mean that all elements have an equal chance to appear. (25%)
Now, let's say we take this array : (a,b,c,d,d).
Here we still have 4 elements, but not every one of them has equal chances to appear.
a,b,c : 20%
d : 40%
Or, let's take this array :
(1,2,3,...,97,97,97,98,98,98,99,99,99,100,100,100,100)
Hint : This way you won't only bias the random number generation algorithm, but you'll actually set the desired probability of apparition of each one (or of a range of numbers).
So, that's how I would go about that :
If you want numbers from 1 to 100 (with higher numbers appearing more frequently, get a random number from 1 to 1000 and associate it with a wider range. E.g.
rand = 800-1000 => rand/10 (80->100)
rand = 600-800 => rand/9 (66->88)
...
Or something like that. (You could use any math operation you imagine, modulo or whatever... and play with your algorithm). I hope you get my idea.
Good luck! :-)
My primary question is:
Is this alot of loops?
while ($decimals < 50000 and $remainder != "0") {
$number = floor($remainder/$currentdivider); //Always round down! 10/3 =3, 10/7 = 1
$remainder = $remainder%$currentdivider; // 10%3 =1, 10%1
$thisnumber = $thisnumber . $number;
$remainder = $remainder . 0; //10
$decimals += 1;
}
Or could I fit more into it? -without the server crashing/lagging.
I'm just wondering,
Also is there a more effiecent way of doing the above? (e.g. finidng out that 1/3 = 0.3 to 50,000 decimals.)
Finally:
I'm doing this for a pi formulae the (1 - 1/3 + 1/5 - 1/7 etc.) one,
And i'm wondering if there is a better one. (In php)
I have found one that finds pi to 2000 in 4 seconds.
But thats not what I want. I want an infinite series that converges closer to Pi
so every refresh, users can view it getting closer...
But obv. converging using the above formulae takes ALONG time.
Is there any other 'loop' like Pi formulaes (workable in php) that converge faster?
Thanks alot...
Here you have several formulas for calculating Pi:
http://mathworld.wolfram.com/PiFormulas.html
All of them are "workable" in PHP, like in any other programming language. A different question is how fast they are or how difficult they are to implement.
If the formulas converge faster or slower, it's a Math question, not about programming, so I can't help you. I can tell you that as a rule of a thumb, the less nested loops you put, the faster will be your algorithm (this is a general rule, don't take it as the absolute truth!)
Anyway, since the digits of Pi are known until a certain digit, why don't you copy it into a file and then just index it? That will be extremely fast :)
You can check previous answers to similar questions:
How can pi be calculated to a set number of digits in PHP?
https://stackoverflow.com/questions/3045020/which-is-the-best-formulae-to-find-pi
Check http://mathworld.wolfram.com/PiIterations.html (taken from the last answer). Those formulaes are using iterations and can therefor be implemented using a loop.
You should use google and search for "php implementation xxxxxxx" (where xxxxxx stands for the algorithm name you want to search for).
EDIT: Here is an implementation of Vietas formula using a while-loop in php.