How to solve nth degree equations in PHP
Example:
1/(1+i)+1/(1+i)2+...1/(1+i)n=k
While k is the constant,I'd like to find value of i.
How can I achieve this in PHP?
First of all, your expression on the left is a geometric sum, so you can rewrite it as (using x=1+i)
1/x*(1+...+1/x^(n-1)) = 1/x * (1-1/x^n)/(1-1/x) = (1-x^(-n))/(x-1)
and consequently the equation can be rewritten as
(1 - pow( 1+i, -n))/i = k
Now from the original expression one knows that the left side as a sum of convex monotonically decreasing functions is equally so, thus any of bisection, regula falsi variants or secant method will work sufficiently well.
Use
(1+i)^(-n)=1 - n*i + (n*(n+1))/2*i^2 +...
to get the approximative equation and first approximation
1-(n+1)/2*i = k/n <=> i = (1-k/n)*2/(n+1)
so that you can start bracketing method with the interval from 0 to twice this i.
Try something like this....
$n = 5;
$i = 2;
$k = null;
for ($x = 1; $x <= $n; $x++) {
$k += 1 / pow((1 + $i), $x);
}
echo $k; //Answer --> 0.49794238683128
Related
I'm reading "PHP 7 Data Structures and Algorithms" chapter "Shortest path using the Floyd-Warshall algorithm"
the author is generating a graph with this code:
$totalVertices = 5;
$graph = [];
for ($i = 0; $i < $totalVertices; $i++) {
for ($j = 0; $j < $totalVertices; $j++) {
$graph[$i][$j] = $i == $j ? 0 : PHP_INT_MAX;
}
}
i don't understand this line :
$graph[$i][$j] = $i == $j ? 0 : PHP_INT_MAX;
looks like a one line if statement
is it the same as ?
if ($i == $j) {
$graph[$i][$j] = 0;
} else {
$graph[$i][$j] = PHP_INT_MAX;
}
what is the point of using PHP_INT_MAX ?
at the end what does the graph look like ?
You've correctly understood the ternary (? :) operator
To answer the other part of your question, have a look if the following makes sense to you.
First:
The author initializes the $graph array using the following code:
<?php
$totalVertices = 5; // total nodes (use 0, 1, 2, 3, and 4 instead of A, B, C, D, and E, respectively)
$graph = [];
for ($i = 0; $i < $totalVertices; $i++) {
for ($j = 0; $j < $totalVertices; $j++) {
$graph[$i][$j] = $i == $j ? 0 : PHP_INT_MAX;
}
}
which results in the following matrix
All the nodes(vertices) on the main diagonal(grey) are set to 0 as a node's distance to itself equals 0.
All the remaining nodes in the 'matrix' are set to PHP_INT_MAX (the largest integer supported) - we'll see why this is in a minute.
Second:
The author then sets the distances between the nodes that have a direct connection(edges), writing them manually to the $graph array, as follows:
$graph[0][1] = $graph[1][0] = 10;
$graph[2][1] = $graph[1][2] = 5;
$graph[0][3] = $graph[3][0] = 5;
$graph[3][1] = $graph[1][3] = 5;
$graph[4][1] = $graph[1][4] = 10;
$graph[3][4] = $graph[4][3] = 20;
This results in the following 'matrix' stored in array $graph (green: edge distances):
So why does the author use PHP_INT_MAX for the nodes that are not directly connected(the non-edges)?
The reason is, because it allows for the algorithm to work with
node-connection(edge) distances up to and including PHP_INT_MAX.
In this particular example, any number smaller than 20 in stead of PHP_INT_MAX in the ternary would warp the outcomes of the algorithm - it would spit out wrong results.
Or another way to look at this, in this particular example the author could have just used any number bigger than 20 in stead of PHP_INT_MAX to get satisfactory results from the algorithm,
because the biggest distance between two directly connected nodes in this case equals 20. Use any number smaller than 20 and the results will come out wrong.
You can give it a try, and test:
$graph[$i][$j] = $i == $j ? 0 : 19;
the algorithm will now tell us that the shortest distance between A to E - i.e. $graph[0][4] equals 19... WRONG
So using PHP_INT_MAX here gives 'leeway', it allows for the algorithm to work successfully with edge distances smaller than or equal to 9223372036854775807 (the largest int that can be stored on a 64 bit system),
or 2147483647 (on a 32 bit system).
You have two questions here.
The first is regarding the syntax condition ? val_if_true : val_if_false. This is called the "ternary operator". Your assessment regarding the behavior is correct.
The second is regarding the use of PHP_INT_MAX. All distances between two nodes are being initialized to one of two values: 0 if nodes i and j are the same node (i.e. a vertex), and PHP_INT_MAX if the nodes are not the same (i.e. an edge). That is, a node's distance to itself is 0 and a node's distance to any other node is the largest integer value PHP recognizes. The reason for this is that the Floyd-Warshall algorithm utilizes the concept of "infinity" to represent minimum distances that have not yet been calculated, but as there is no concept of "infinity" in PHP, the value PHP_INT_MAX is being used as a stand-in for it.
My task, using php, is to create a random number, then make that number multiply itself. However i cannot use the multiply operator (*) and have been told to create a for loop instead however I'm having some troubles.
$startNum = rand(1,10);
for ($i = $startNum; $i <= 10; $i++)
{
echo $i;
}
This is what i have so far, however this is completely wrong and will only get a random number and count to 10 from it.
Any help would be very appreciated, thanks.
When squaring you are just multiplying a number by itself, another way to do this is through addition, add a number to itself x amount of times. So, with 4 squared, that is 4 * 4 or, 4 + 4 + 4 + 4.
Doing this in a for loop should be as simple as
$startNum = rand(1,10);
$endNum = 0;
for ($i = 0; $i < $startNum; $i++)
{
$endNum += $startNum;
}
echo $endNum;
Caveat: I don't program Php so forgive syntax errors.
$startNum*$startNum means that the loop should loop $startNum times and in each iteration add $startNum, i.e., the number itself
$s = 0;
for($i=1;$i<=$startNum;$i++){
$s += $startNum;
}
echo $s;
Still not using the multiplication operator :p
$n = mt_rand(1, 10);
echo array_sum(array_fill(0, $n, $n));
you can do this by simple addition(+) operator
square means add that number into same number for same time.
example : square of 2 means : 2+2;
square of 4 means : addition of 4 with 4 for 4 times : 4+4+4+4
so you can do like that
$startNum = rand(1,10);
$ans=0;
for ($i = 0 ;$i < $startNum; $i++)
{
echo $ans+=$startNum;
}
I tried to do something like that:
$total = 0;
for ($j = 0; $j < 1000; $j++) {
$x = $j / 1000;
$total += pow($x, 1500) * pow((1 - $x), 500);
}
$total is 0.
PHP can't work with too small float values. What can I do? Which libraries can I use?
The function
f(x) = x^1500 * (1-x)^500
has (logarithmic) derivative
f'(x)/f(x)=d/dx log(f(x))
= 1500/x - 500/(1-x)
which is zero for
x0 = 3/4
having the maximum value of
f(3/4) = 3^1500/2^4000 = exp(-1124.6702892376163)
= 10^(-488.4381005764309)
= 3.646694848749686e-489
Using that as reference value, one can now sum up
f(i/1000)/f(3/4)=exp(1500*log(i/1000)+500*log(1-i/1000)+1124.6702892376163)
giving a sum of 24.26257515625789 so that the desired result is
24.26257515625789*f(3/4)=8.847820783972776e-488
A practical way to compute such a sum would be to compute the list of logarithms (more python than PHP, look up the corresponding array operations)
logf = [ log(f(i/1000.0)) for i=1..999 ]
using the transformed logarithm of f, log(f(x))=1500*log(x)+500*log(1-x).
Then compute maxlogf = max(logf), extract the number N=floor(maxlogf/log(10)) of the decimal power and compute the sum as
sumfred = sum([ exp( logfx - N*log(10) ) for logfx in logf ])
so that the final result is sumfred*10^N.
I found this perfect answer for the Codility's PermMissingElem Question.
function solution($A) {
$N = count($A);
$sum = ($N + 2) * ($N + 1) / 2;
for($i = 0; $i < $N; $i++){
$sum -= $A[$i];
}
return intval($sum);
}
However I found its puzzled for me regarding the $sum's function. What kind of function is this? It's amazingly correctly, yet, how come someone could make up such function? Is there anyone can somehow reverse engineer the thinking process?
I really want to know the process how it came about.
Thank You !
The sum of integers from 1 to N can be calculated by this formula:
N(N+1)/2
Basically, you take the first number and the last number and add them together, and then the second number and the second to last number..etc.
For example:
The sum of 1 to 100:
(1+100) + (2+99) + (3+98) + (4+97) ...
= (100/2)(101)
= 50 x 101
Here's a good explanation:
http://www.wikihow.com/Sum-the-Integers-from-1-to-N
Am new to php i have faced an interview some days ago, and the interviewer asked a question like the following one.
The given array has 99 numbers, which contains the digits from 1 to 100
with one digit missing. Describe two different algorithms that finds you the missing number. The algorithm should optimize for low storage and fast processing. Output should show the execution time of each algorithm.
And i have searched google about it, and come to know its a common puzzle used to ask in interviews. I found out the answer like this way.
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
idx = i;
} else {
sum += arr[i];
}
}
// the total sum of numbers between 1 and arr.length.
int total = (arr.length + 1) * arr.length / 2;
System.out.println("missing number is: " + (total - sum) + " at index " + idx);
But the code is not in php,
Can u please help me to find out the php code and algorithm name. So i can improve my answer in the next interviews.
In PHP you can easily use some array functions and achieve that. Best way is,
$missing = array_diff(range(1,100),$array);
DEMO.
Another way to do it is by using the array_sum function and the knowledge that all numbers from 1 to 100 added together equals 5050.
$missing = 5050-array_sum($array);
Converted to PHP, it is nearly the same.
(Not tested)
Of course, there are better ways, like the one Rikesh posted, but this is the exact one you asked for:
$sum = 0
$idx = -1
for($i = 0; $i < count($arr); $i++){
if($arr[$i] == 0){
$idx = $i;
}else{
$sum += $arr[$i];
}
}
$total = (count($arr) + 1) * (count($arr) / 2);
echo "Missing: " . ($total - $sum) . " at index " . $idx;
$arr=range(1,99);
$j=1;
for($i=0;$i<100;$i++){
if(!in_array($j,$arr)){
echo $j.'is missing';
}
$j++;
}