Skip to main content

How to translate this Math Formula in PHP?


I'm trying to convert a Math Formula into PHP code.



You can see the formula in the accepted answer here: Applying a Math Formula in a more elegant way (maybe a recursive call would do the trick) .



I'm not a professional coder so I'm trying my best to translate it but my skills are limited and I've encountered several problems.



Let's start.



There's a vector containing players' stacks: I think a bidimensional array should do the work here. I'd add a key to identify each player.




$array = array(1 => 2000, 3 => 5000 ...);



Now he wants to create a Matrix of values, I did my researches and found a PEAR package called Math_Matrix, installed it but I'm wondering how to create that sort of matrix.



I'm worried that I won't be able to translate the entire code because he uses advances methods like recursive calls etc.



Could you please take a look there and help me?



Thanks



EDIT: BOUNTY REWARD



I tried what you've suggested but I feel like wasting my time becouse of my poor-programming skills.



I'VE DECIDED TO OFFER A 50 BOUNTY IF SOMEONE WANTS TO HELP ME BY TRANSLATING THAT FORMULA IN PHP.



Note that if you think that translating in Python is easier/more suitable/other, please provide me a way to include the Python script inside a PHP script since I'm planning to use this formula in a website.



Have a nice day! :) Hope someone will solve this.


Source: Tips4allCCNA FINAL EXAM

Comments

  1. Here you go.

    I place this code into the public domain.

    # Function to make an array of 'width' zeros
    function makerow($width){
    $row=array();
    for($x=0;$x<$width;$x++){
    $row[$x]=0;
    }
    return $row;
    }

    # Function to make a width*height matrix
    function makematrix($width,$height){
    $matrix=array();
    for($y=0;$y<$height;$y++){
    $matrix[$y]=array();
    for($x=0;$x<$width;$x++){
    $matrix[$y][$x]=0;
    }
    }
    return $matrix;
    }

    # Adds one matrix to another
    function matrixadd(&$matrixdest,&$matrixsrc){
    for($i=0;$i<count($matrixdest);$i++){
    for($j=0;$j<count($matrixdest[$i]);$j++){
    $matrixdest[$i][$j]+=$matrixsrc[$i][$j];
    }
    }
    }

    # Multiplies a matrix by a scalar
    function matrixmultiply(&$matrix,$scalar){
    for($i=0;$i<count($matrix);$i++){
    for($j=0;$j<count($matrix[$i]);$j++){
    $matrix[$i][$j]*=$scalar;
    }
    }
    }

    # Calculates the equity of each place. Rows indicate players;
    # columns indicate places (0 is 1st place, 1 is second, and so on)
    # The parameter 'places' is optional. If not given, uses the
    # number of stacks.
    function equitymatrix(&$stacks, $places=-1){
    if($places==-1){
    # replace places with the stack count
    $places=count($stacks);
    }
    if(count($stacks)<=1){
    return array(array(1));
    }
    $totalStacks=0;
    for($i=0;$i<count($stacks);$i++){
    $totalStacks+=$stacks[$i];
    }
    # Optimize for case where there is only one place
    if($places==1){
    $matrix=makematrix(1,count($stacks));
    for($i=0;$i<count($stacks);$i++){
    $matrix[$i][0]=$stacks[$i]*1.0/$totalStacks;
    }
    return $matrix;
    }
    # Optimize for case where there are two places
    if($places==2){
    $matrix=makematrix(2,count($stacks));
    for($i=0;$i<count($stacks);$i++){
    $matrix[$i][0]=$stacks[$i]*1.0/$totalStacks;
    }
    for($i=0;$i<count($stacks);$i++){
    for($j=0;$j<count($stacks);$j++){
    if($i!=$j){
    $matrix[$i][1]+=$matrix[$j][0]*($stacks[$i]*1.0/($totalStacks-$stacks[$j]));
    }
    }
    }
    return $matrix;
    }
    # Calculate the probabilities of each player getting first place
    $probabilities=array();
    for($i=0;$i<count($stacks);$i++){
    $probabilities[$i]=$stacks[$i]*1.0/$totalStacks;
    }
    #echo(count($stacks)." ".$places."\n");
    $subequities=array();
    for($i=0;$i<count($stacks);$i++){
    $substacks=array();
    # Assume that player i would be in first place
    # Create a new array with i's stack removed
    for($j=0;$j<count($stacks);$j++){
    if($j!=$i){
    array_push($substacks,$stacks[$j]);
    }
    }
    # Find the subequity of the remaining players
    $subequities[$i]=equitymatrix($substacks,
    min($places,count($substacks)));
    for($j=0;$j<count($subequities[$i]);$j++){
    array_unshift($subequities[$i][$j],0);
    }
    # Add player i back
    $newrow=makerow($places);
    $newrow[0]=1;
    array_splice($subequities[$i],$i,0,array($newrow));
    }
    $equities=makematrix($places,count($stacks));
    for($i=0;$i<count($stacks);$i++){
    # Multiply the probabilities
    matrixmultiply($subequities[$i],$probabilities[$i]);
    # Add the subequity
    matrixadd($equities,$subequities[$i]);
    }
    return $equities;
    }


    Example:

    $mystacks=array(10,40,30,20);
    print_r(equitymatrix($mystacks));




    As to the use of matrices:

    In PHP, a matrix can be represented as an array of arrays. You can see
    that in the function makematrix, which returns an array of length height,
    with each element being an array of width zeros. Your problem uses the following
    matrix operations, both of which are simple:


    Adding two matrices (matrixadd). Here, just add the elements of one matrix to the
    corresponding elements of the other matrix.
    Multiplying a matrix by a single number (a scalar) (matrixmultiply) simply
    involves multiplying each element of the matrix by that number.

    ReplyDelete
  2. I guess the biggest question is what you plan to use this for. In the end I would really recommend against using PHP. Its not designed for this type of work and you'll end up causing a lot of work for yourself later.

    If you are just looking for a means of calculating it, I would recommend using Octave (The OpenSource Version of MATLAB) If you actually want to build a program around it, you should look into Python using the NumPy module: http://numpy.scipy.org/



    If you have the ability, I would recommend using mod_python for running NumPy to handle this. It would likely be the simplest means of doing it as NumPy can natively handle Matrices. Barring that, you should look at the following classes that exist for handling matrices in PHP. Some individuals have developed some classes designed specifically for manipulating Matrices.

    http://www.phpkode.com/scripts/item/matrix-new/
    http://www.phpclasses.org/package/2859-PHP-Perform-operations-with-matrices.html

    ReplyDelete
  3. If you have Matlab installed, with the symbolic math toolbox,

    you can use the ccode function in order to translate this formula (or any other) to c-code (which is very similar to php).

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.