How can I make calculation pieces in PHP? - php

How can I make calculation pieces in PHP?
This is my calculation
605,00 / 5% = 30.25.
How can I calculate this in PHP?
$a = 605.00;
$b = 5 (percentage)
How I have tried, but this did not work
$total = ($a / 0.5);

You could do:
$number = 605;
$percentage = 5;
$total = $number * ($percentage / 100);

Actually if you divide 5 by 100, it will equal 0.05 so try $b = .05;.
In basic math, the first decimal is calculated in 10ths, then 100ths, then 1000ths
Just do $total = ($a / $b);
Tested. Total = 12,100 yet will echo 12100
<?php
$a = 605.00;
$b = 0.05;
$total = ($a / $b);
echo $total; // will echo 12100
?>

Related

PHP generate cent value of entered amount

In my database I store the amount of a user in cents.
Now I need to convert user input to integer.
input of user(string) :|output (int):
1.00 100
1 100
1,51 151
I have no idea, how to solve this. Formatting amounts like: 1.00 and 1,00 isn't a big problem, but what's the best way to format the amount like "1" to the right amount of cents?
What I use at the moment (not working with inputs like "1"):
$value = intval(str_replace([',','.'],'', $request->amount));
What about casting as a float and multiplying by 100?
<?php
header("Content-type: text/plain");
$x = '1,51';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";
$x = '1';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";
$x = '1.51';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";
$x = '1,00';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";
$x = '1.00';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";
returns:
151
100
151
100
100
str_replace should be used with two arrays or two strings
$value = intval(str_replace([',','.'],['',''], $request->amount));

Round down to nearest multiple of 10000 using PHP

If I have the following code which grabs an array of values and adds them all together, how can I then round them down to the nearest 10000 using PHP?
Here's the code I currently have
$rows = $db->get("sales");
$sales = 0;
foreach($rows as $row) {
$stock = $sales + $row['sales'];
}
return $sales;
An example result would be
146740
How could I then make that returned as
140000
Although if I had a number greater than 1 million, how could I have that returned as just 1 million?
Divide by 10000, use floor to round down to an integer, then multiply by 10000:
$x = 146740;
$x = 10000 * floor($x/10000);
Or subtract the remainer:
$x = 146740;
$x = $x - ($x % 10000);
To extend this to 1 million, you can do:
if ($x > 1000000) {
$divisor = 1000000;
} elseif ($x > 10000) {
$divisor = 10000;
} else {
$divisor = 1;
}
$x = $x - ($x % divisor);
you could divide the value by 1000. If it is integer 146740/1000 = 146. And after that multiply by 1000 will give 146000

Adding and subtracting within a range of numbers and looping round

I'm wondering how I would go about the addition and subtraction of numbers in a set range and which would loop back on themselves, example below;
Range: 1 - 10
So if I now had the number 7 and added 5 to it, I would want the number go to 2
8, 9, 10, loop around to 1, 2.
And the same if I subtracted, so I have the number 3 and I subtract 4 so I should be left with 9.
2, 1, loop around to 10, 9
I hope this makes sense.
Thanks.
You can use % operator.
It calculates remainder after division.
For example:
$d = 10;
$x = 7;
$y = 5;
echo ($x + $y) % $d;
gives 2;
With negative values you can just remove MINUS
Use the modulus operator.
result = (a + b) % 10;
You can use modulo function like (7+5)%10 = 2
Try this:
$range = range(1,10);
$min = min($range);
$max = max($range);
function operate( $a, $b, $operation ) {
global $max, $min;
switch( $operation ) {
case '+':
$a += $b;
break;
case '-':
$a -= $b;
break;
}
if( $a < $min ) {
return $max + $a;
} else if( $a > $max ) {
return $a - $max;
}
}
Hope it helps.
You can do this with code like
$range = array('from' => 3, 'to' => 13);
$dist = $range['to'] - $range['from'];
$a = 7;
$b = 14;
echo ($dist + ($a % $range['to'] - $b % $range['to'])) % $dist; // $a - $b
echo ($dist + ($a % $range['to'] + $b % $range['to'])) % $dist; // $a + $b
Modulo will do the trick as others have shown, but you must also account for the lower end of the range.
E.g. looping an arbitrary value within an hour range will work since it's zero-based. But if you want to loop a value within a month range you will get into trouble with the last day, because:
31 % 31 = 0
So you will loop to zero when you should remain on 31.
To deal with any range, you need to do this:
$min = 5;
$max = 15;
$value = 25; // The range is 11, so we want this turned into 14
$range = $max - $min + 1;
$value = (($value-$min) % $range) + $min;
To deal with values below minimum:
$range = $max - $min + 1;
$value = ($min - $value) % $range;
$value = $max - ($value - 1);

Find what 2 numbers add to something and multiply to something

Hey so I'm making a factoring program and I'm wondering if anyone can give me any ideas on an efficient way to find what two numbers multiple to a specified number, and also add to a specified number.
for example I may have
(a)(b) = 6
a + b = 5
So essentially i just need a way to find the a and b values. In this case they would be 2 and 3.
Can anyone give me any ideas on where to start? Negative numbers must also be considered for use.
There is no need to loop, just use simple math to solve this equation system:
a*b = i;
a+b = j;
a = j/b;
a = i-b;
j/b = i-b; so:
b + j/b + i = 0
b^2 + i*b + j = 0
From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.
There you go:
function finder($add,$product)
{
$inside_root = $add*$add - 4*$product;
if($inside_root >=0)
{
$b = ($add + sqrt($inside_root))/2;
$a = $add - $b;
echo "$a+$b = $add and $a*$b=$product\n";
}else
{
echo "No real solution\n";
}
}
Real live action:
http://codepad.org/JBxMgHBd
Here is how I would do that:
$sum = 5;
$product = 6;
$found = FALSE;
for ($a = 1; $a < $sum; $a++) {
$b = $sum - $a;
if ($a * $b == $product) {
$found = TRUE;
break;
}
}
if ($found) {
echo "The answer is a = $a, b = $b.";
} else {
echo "There is no answer where a and b are both integers.";
}
Basically, start at $a = 1 and $b = $sum - $a, step through it one at a time since we know then that $a + $b == $sum is always true, and multiply $a and $b to see if they equal $product. If they do, that's the answer.
See it working
Whether that is the most efficient method is very much debatable.
With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:
$factors = array();
for($i = 0; $i < $target; $i++){
if($target % $i == 0){
$temp = array()
$a = $i;
$b = $target / $i;
$temp["a"] = $a;
$temp["b"] = $b;
$temp["index"] = $i;
array_push($factors, $temp);
}
}
This would leave you with an array of factors of the target number.
That's basically a set of 2 simultaneous equations:
x*y = a
X+y = b
(using the mathematical convention of x and y for the variables to solve and a and b for arbitrary constants).
But the solution involves a quadratic equation (because of the x*y), so depending on the actual values of a and b, there may not be a solution, or there may be multiple solutions.

How can I calculate a trend line in PHP?

So I've read the two related questions for calculating a trend line for a graph, but I'm still lost.
I have an array of xy coordinates, and I want to come up with another array of xy coordinates (can be fewer coordinates) that represent a logarithmic trend line using PHP.
I'm passing these arrays to javascript to plot graphs on the client side.
Logarithmic Least Squares
Since we can convert a logarithmic function into a line by taking the log of the x values, we can perform a linear least squares curve fitting. In fact, the work has been done for us and a solution is presented at Math World.
In brief, we're given $X and $Y values that are from a distribution like y = a + b * log(x). The least squares method will give some values aFit and bFit that minimize the distance from the parametric curve to the data points given.
Here is an example implementation in PHP:
First I'll generate some random data with known underlying distribution given by $a and $b
// True parameter valaues
$a = 10;
$b = 5;
// Range of x values to generate
$x_min = 1;
$x_max = 10;
$nPoints = 50;
// Generate some random points on y = a * log(x) + b
$X = array();
$Y = array();
for($p = 0; $p < $nPoints; $p++){
$x = $p / $nPoints * ($x_max - $x_min) + $x_min;
$y = $a + $b * log($x);
$X[] = $x + rand(0, 200) / ($nPoints * $x_max);
$Y[] = $y + rand(0, 200) / ($nPoints * $x_max);
}
Now, here's how to use the equations given to estimate $a and $b.
// Now convert to log-scale for X
$logX = array_map('log', $X);
// Now estimate $a and $b using equations from Math World
$n = count($X);
$square = create_function('$x', 'return pow($x,2);');
$x_squared = array_sum(array_map($square, $logX));
$xy = array_sum(array_map(create_function('$x,$y', 'return $x*$y;'), $logX, $Y));
$bFit = ($n * $xy - array_sum($Y) * array_sum($logX)) /
($n * $x_squared - pow(array_sum($logX), 2));
$aFit = (array_sum($Y) - $bFit * array_sum($logX)) / $n;
You may then generate points for your Javascript as densely as you like:
$Yfit = array();
foreach($X as $x) {
$Yfit[] = $aFit + $bFit * log($x);
}
In this case, the code estimates bFit = 5.17 and aFit = 9.7, which is quite close for only 50 data points.
For the example data given in the comment below, a logarithmic function does not fit well.
The least squares solution is y = -514.734835478 + 2180.51562281 * log(x) which is essentially a line in this domain.
I would recommend using library: http://www.drque.net/Projects/PolynomialRegression/
Available by Composer: https://packagist.org/packages/dr-que/polynomial-regression.
In case anyone is having problems with the create_function, here is how I edited it. (Though I wasn't using logs, so I did take those out.)
I also reduced the number of calculations and added an R2. It seems to work so far.
function lsq(){
$X = array(1,2,3,4,5);
$Y = array(.3,.2,.7,.9,.8);
// Now estimate $a and $b using equations from Math World
$n = count($X);
$mult_elem = function($x,$y){ //anon function mult array elements
$output=$x*$y; //will be called on each element
return $output;
};
$sumX2 = array_sum(array_map($mult_elem, $X, $X));
$sumXY = array_sum(array_map($mult_elem, $X, $Y));
$sumY = array_sum($Y);
$sumX = array_sum($X);
$bFit = ($n * $sumXY - $sumY * $sumX) /
($n * $sumX2 - pow($sumX, 2));
$aFit = ($sumY - $bFit * $sumX) / $n;
echo ' intercept ',$aFit,' ';
echo ' slope ',$bFit,' ' ;
//r2
$sumY2 = array_sum(array_map($mult_elem, $Y, $Y));
$top=($n*$sumXY-$sumY*$sumX);
$bottom=($n*$sumX2-$sumX*$sumX)*($n*$sumY2-$sumY*$sumY);
$r2=pow($top/sqrt($bottom),2);
echo ' r2 ',$r2;
}

Categories