how to write VAR.P excel function in PHP - php

I'm trying to cacluate the variance of an array in PHP and I can' use built in "stats_variance" function.
I've searched a lot and found a few functions in php to calculate Variance But the problem is that the number that "VAR.P" excel functions calculates is way different in php.
This is my Array of data :
1153680
1118118
1118912
1116187
1068844
1028538
1028538
988121
970411
973495
938557
938550
926133
959840
959841
986759
986759
1002125
995177
968461
987475
1017662
1021445
1047763
1043253
1020218
977923
977923
980571
979106
956817
917406
878101
878094
845952
820505
797824
769385
741932
741902
726137
708995
690126
668906
645763
645723
626389
624527
623260
607855
597254
597069
583344
569674
573903
567532
547658
545661
532522
521267
520108
508879
512900
512903
502077
505943
494479
502694
520211
520210
520059
535684
549185
555167
555165
543926
529170
515452
505676
523850
524394
517911
503306
498856
480875
478755
478754
472119
476812
472749
461988
459079
447151
454618
452842
445894
440199
438880
428216
426184
427139
420668
418312
417001
411211
406008
409807
410694
409962
399445
395912
392038
375650
359807
353807
358843
365815
367334
384099
377012
375547
369729
367632
361088
362259
359365
356721
353996
350322
346870
344487
344115
343291
339386
339434
335792
332567
327624
322527
320814
320194
318670
314587
311230
309643
308477
305774
305622
304997
304688
302726
302340
306885
307094
306655
303944
302795
305858
305333
304676
308960
308730
309661
305969
303449
303453
305807
308314
302173
301391
309640
308978
319871
326190
322059
313049
314469
320909
320208
327305
326117
326098
324705
318250
320023
314409
312206
311471
297712
294166
302082
305917
302395
304460
299930
296731
294601
290178
285573
283062
And the calculated variance in excel using VAR.P function is "61222801119"
This is one of the functions that I have tried
function getVariance1($arr){
$arr_size=count($arr);
$mu=array_sum($arr)/$arr_size;
$ans=0;
foreach($arr as $elem){
$ans+=pow(($elem-$mu),2);
}
return sqrt($ans/$arr_size);
}
which returns "1633416980.1583" that is way wrong.
What's the problem ?
Thanks

Related

Math issue in php

I'm trying to get percentage of two numbers in my app (laravel based) but i don't get the right numbers.
Code:
$pdts->price = 123.234
$pdts->newprice = 90.500
{{number_format($pdts->newprice / $pdts->price * 100, 0) } }%
it returns -73%, it should return -27%. How do I correct this?
Update To those still didn't get it
Guys I did defined my goal / what i'm looking for it should return -27%. How do I correct this? so I was looking to get -27% as the result and thanks to commenters I did find my solution.
I don't understand all this vote-downs and continued comments.
This is not really a programming question, it's more a math question.
But to get the result you want you need to calculate the difference in percentage.
//(123.234-90.500)/123.234*100
- {{number_format(($pdts->price - $pdts->newprice) / $pdts->price * 100, 0) } }%
// -27%
Try this one,
$value = ($pdts->price-$pdts->newprice) / $pdts->price * 100;
$percentage = (int)($value).'%';
Here, percentage variable will have your required value.

PHP code to replace certain values in array, code generator

I am trying to write PHP code as a hobby project to basically create a "possible" code generator. The scenario is that we have a list of 25 valid characters that can be used.
Imagine that you have a 25 character code but you have accidentally scratched off the first two characters or three characters at any location in the code. Now we need to find all the possible combinations to try out. I have put all the valid characters into the array below that can be used in the code.
$valid=array("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","Z",
"2","3","4","6","7","8","9");
$arraylength=count($valid);
The still available or seen characters are input into a text box and in the place where the character is unreadable is left blank and the variable values are fetched.
$char1= $_POST['code1'];
$char2= $_POST['code2'];
$char3= $_POST['code3'];
$char4= $_POST['code4'];
$char5= $_POST['code5'];
$char6= $_POST['code6'];
$char7= $_POST['code7'];
$char8= $_POST['code8'];
$char9= $_POST['code9'];
$char10= $_POST['code10'];
$char11= $_POST['code11'];
$char12= $_POST['code12'];
$char13= $_POST['code13'];
$char14= $_POST['code14'];
$char15= $_POST['code15'];
$char16= $_POST['code16'];
$char17= $_POST['code17'];
$char18= $_POST['code18'];
$char19= $_POST['code19'];
$char20= $_POST['code20'];
$char21= $_POST['code21'];
$char22= $_POST['code22'];
$char23= $_POST['code23'];
$char24= $_POST['code24'];
$char25= $_POST['code25'];
And put into an array...
$jada = array($char1, $char2, $char3, $char4, $char5, $char6, $char7, $char8, $char9, $char10, $char11, $char12, $char13, $char14, $char15
, $char16, $char17, $char18, $char19, $char20, $char21, $char22, $char23, $char24, $char25);
I have been stumped for a while now, the fiddling I have done at the moment is that if a variable is empty then do something (as a test echo or print the possible combinations)
if(!isset($char1) || trim($char1) == ""){
for($x=0;$x<$arraylength;$x++) {
echo $valid[$x];
echo "<br>";
} }
else{
echo ($char1);
}
Can you guys help out?
Saw this still in an open status after many years of hiatus, I figured that I may as well share some information.
In the end I figured it out, you can grab the source here and test it in your own server: https://github.com/Masterkriz/XBOX_Pre-paid_code_fixer

Unable to get stat gathering to work

Using PHP to gather stats from multiple files. Goal is to take the entire first row of data, which is the column name, then take the entire row of data from the row where the first column matches the name specified in the code. These two rows should then be linked to each other, so they can be displayed in a dynamic image.
However, to avoid excessive requests from the external data source, the data is only downloaded once a day by saving it into a json file. The previous day's data is also kept, to perform a difference calculation.
What I'm stuck on is...well, it's not working as intended. The dynamic image does not display and says it cannot be displayed because it contains errors, and the files aren't being created properly. Without any files existing, only the 'old' data file is being created, and the gathered data is saved there in a format that I didn't expect.
Here's the entire PHP code:
<?php
header("Content-Type:image/png");
$root=realpath($_SERVER['DOCUMENT_ROOT']);
function saveTeamData(){
$urls=array('http://www.dc-vault.com/stats/bio.txt','http://www.dc-vault.com/stats/math.txt','http://www.dc-vault.com/stats/misc.txt','http://www.dc-vault.com/stats/overall.txt','http://www.dc-vault.com/stats/phys.txt');
$fullJson=array();
function stats($url){
$json=array();
$team=array("teamName");
$file=fopen($url,'r');
$firstRow=fgetcsv($file,0,"\t");
while($data=fgetcsv($file,0,"\t")){
if(in_array($data[0],$team)){
foreach($firstRow as $indx=>$colName){
if((strpos($colName,'Position')!=0)||(strpos($colName,'Score')!=0)||(strpos($colName,'Team')!=0)){
if(strrpos($colName,'Position')!==false){
$colName=substr($colName,0,strpos($colName,' Position'));
$colName=$colName."Pos";
}else{
$colName=substr($colName,0,strpos($colName,' Score'));
$colName=$colName."Score";
}
$colName=str_replace(' ',',',$colName);
$teamData[$colName]=$data[$indx];
}
}
$json=$teamData;
}
}
fclose($file);
return $json;
}
foreach($urls as $item){
$fullJson=array_merge($fullJson,stats($item));
}
$final_json['teamName']=$fullJson;
$final_json['date']=date("Y-m-d G:i:s",strtotime("11:00"));
$final_json=json_encode($final_json);
file_put_contents("$root/scripts/vaultData.js",$final_json);
return $final_json;
}
if(!file_exists("$root/scripts/vaultData.js")){
$teamData=saveTeamData();
}else{
$teamData=json_decode(file_get_contents("$root/scripts/vaultData.js"));
}
$lastDate=$teamData->date;
$now=date("Y-m-d G:i:s");
$hours=(strtotime($now)-strtotime($lastDate))/3600;
if($hours>=24||!file_exists("$root/scripts/vaultDataOld.js")){
file_put_contents("$root/scripts/vaultDataOld.js",json_encode($teamData));
$teamData=saveTeamData();
}
$team=$teamData->{"teamName"};
$teamOld=json_decode(file_get_contents("$root/scripts/vaultDataOld.js"))->{"teamName"};
$template=imagecreatefrompng("$root/images/vaultInfo.png");
$black=imagecolorallocate($template,0,0,0);
$font='images/fonts/UbuntuMono-R.ttf';
$projects=array();
$subsections=array();
foreach($team as $key=>$val){
$projectName=preg_match("/^(.*)(?:Pos|Score)$/",$key,$cap);
$projectName=str_replace(","," ",$cap[1]);
if(preg_match("/Pos/",$key)){
$$key=(strlen($val)>10?substr($val,0,10):$val);
$delta=$key."Delta";
$$delta=($val - $teamOld->{$key});
$$delta=(strlen($$delta)>5?substr($$delta,0,5):$$delta);
if($projectName!=="Overall"){
if(!in_array($projectName,array("Physical Science","Bio/Med Science","Mathematics","Miscellaneous"))){
$projects[$projectName]["position"]=$$key;
$projects[$projectName]["position delta"]=$$delta*1;
}else{
$subsections[$projectName]["position"]=$$key;
$subsections[$projectName]["position delta"]=$$delta*1;
}
}
}elseif(preg_match("/Score/",$key)){
$$key=(strlen($val)>10?substr($val,0,10):$val);
$delta=$key."Delta";
$$delta=($val - $teamOld->{$key});
$$delta=(strlen($$delta)>9?substr($$delta,0,9):$$delta);
if($projectName!=="Overall"){
if(!in_array($projectName,array("Physical Science","Bio/Med Science","Mathematics","Miscellaneous"))){
$projects[$projectName]["score"]=$$key;
$projects[$projectName]["score delta"]=$$delta;
}else{
$subsections[$projectName]["score"]=$$key;
$subsections[$projectName]["score delta"]=$$delta;
}
}
}
}
$sort=array();
foreach($projects as $key=>$row){
$sort[$key]=$row["score"];
}
array_multisort($sort,SORT_DESC,$projects);
$lastupdated=round($hours,2).' hours ago';
$y=35;
foreach($projects as $name=>$project){
imagettftext($template,10,0,5,$y,$black,$font,$name);
imagettftext($template,10,0,149,$y,$black,$font,$project['position']);
imagettftext($template,10,0,216,$y,$black,$font,$project['position delta']*-1);
imagettftext($template,10,0,257,$y,$black,$font,$project['score']);
imagettftext($template,10,0,331,$y,$black,$font,$project['score delta']);
$y+=20;
}
$y=655;
foreach($subsections as $name=>$subsection){
imagettftext($template,10,0,5,$y,$black,$font,$name);
imagettftext($template,10,0,149,$y,$black,$font,$subsection['position']);
imagettftext($template,10,0,216,$y,$black,$font,$subsection['position delta']*-1);
imagettftext($template,10,0,257,$y,$black,$font,$subsection['score']);
imagettftext($template,10,0,331,$y,$black,$font,$subsection['score delta']);
$y+=20;
}
imagettftext($template,10,0,149,735,$black,$font,$team->{'OverallPos'});
imagettftext($template,10,0,216,735,$black,$font,$OverallPosDelta*-1);
imagettftext($template,10,0,257,735,$black,$font,$OverallScore);
imagettftext($template,10,0,331,735,$black,$font,$OverallScoreDelta);
imagettftext($template,10,0,149,755,$black,$font,$lastupdated);
imagepng($template);
?>
And here is what the data looks like when it is saved:
"{\"teamName\":{\"Folding#HomePos\":\"51\",\"Folding#HomeScore\":\"9994.405407\"},\"date\":\"2014-03-14 11:00:00\"}"
I've omitted most of the data because it just makes things excessively long, and it helps to see the format. Now the reason why its an unexpected output is because I didn't expect trailing slashes to be in it. The older version of this code would output like this:
{"teamName":{"Asteroids#HomePos":"192","Asteroids#HomeScore":"7647.783251"},"date":"2014-03-14 11:00:00"}
So the expected behaviour is to to gather the data from the aforementioned rows in each tab delimited text file, copy the old data into the 'old' data file (vaultDataold), save the new data into the 'current' data file (vaultData), and then display the data from the 'current' file in a dynamic image, along with performing a 'new' minus 'old' calculation on the two files to show the change since the previous day.
Most of this code should work, as I've had it working before in a different way. The issue likely lies somewhere with gathering the row data and saving it, most probably the latter. I'm guessing the slashes are causing the issue.
Turns out that the cause was twofold. Firstly, in my function, I was JSON encoding something that had already been encoded, so when the second file was saved, it appeared as shown in my question. To fix that, I did this:
$final_json['date']=date("Y-m-d G:i:s",strtotime("11:00"));
$encode_json=json_encode($final_json);
file_put_contents("$root/scripts/vaultData.js",$encode_json);
return $final_json;
In addition, as pointed out by another in the comments, I had to add $root to my function, and again within it.

How to return multiple values from a function [duplicate]

This question already has answers here:
Multiple returns from a function
(32 answers)
Closed 6 years ago.
I'm building a script to work with PxPost from Payment Express and I've used their sample code as can be found at http://www.paymentexpress.com/Technical_Resources/Sample_code_-_PHP/PX_Post_-_cURL.aspx
How it works: It's built into an automated script that queries orders from my database, processes them, and returns a value.
My only problem is I want the function to return more than one value, so this is what I've done.
Code to run through functions (Line 201):
$once_complete = process_request($billingID, $order_total, $merchRef);
Which send the payment to be processed, that then gets the returns and processes the XML using the sample code. At the end of the code I've removed all the $html info and just replaced it with the following (line 111):
return $CardHolderResponseDescription.":".$MerchantResponseText.":".$AuthCode.":".$MerchantError;
Which should as far as I understand, return that to what started it. I then want to split those values and return them as strings using the following (line 202):
list($RespDesc, $MerchResp, $AuthCode, $MerchError) = explode(":", $once_complete);
But for some reason that's not working.
I've tried echo-ing the return and it works fine then, but then after that it seems to disappear. What may be going wrong?
You can see the entire page's code at http://pastebin.com/LJjFutne. This code is a work in progress.
Return an array.
function process_request(){
...
return array( $CardHolderResponseDescription, $MerchantResponseText, $AuthCode, $MerchantError );
}
And pick it up via:
$_result = process_request();
$CardHolderResponseDescription = $_result[0];
$MerchantResponseText = $_result[1];
...
Tip: use shorter vars for better reading :)
In your function process_request:
return array($CardHolderResponseDescription, $MerchantResponseText, $AuthCode, $MerchantError);
When calling your function:
list($RespDesc, $MerchResp, $AuthCode, $MerchError) = process_request($billingID,$order_total,$merchRef);
The simplest thing you can do is putting the return values in an array which you can access later:
return array("CardHolderResponseDescription"=>$CardHolderResponseDescription, "MerchantResponseText" => $MerchantResponseText, "AuthCode" => $AuthCode );
And later:
list($RespDesc, $MerchResp, $AuthCode, $MerchError) = $my_return_value

Seeding the random number Generator In PHP

I m having a application in which i have to select a number out of many numbers according to their weights. Every time I will select , I have send the result to flash.I have found a algorithm in python. I have implemented it in php and was testing for its results. If i was running that algo in python it was giving good results but in php not so good. Ex. (1=>30,2=>40,3=>30) After running many times , the probablity of occurence first number in weighted array is always more but in python it is uniform. I have attatched the PHP code.
define("MAX",100000);
$reelfrequencies=array(30,40,30);
echo weightedselect($reelfrequencies);
/*function weightedselect($frequency)
{
$arr=cumWghtArray($frequency);//array(35,96,100);
print_r($arr);
$len=sizeof($frequency);
$count=array();
echo $r=mt_rand(0,$arr[$len-1]);
$index=binarysearch($arr,$r,0,$len-1);
return $index;
}*/
function cumWghtArray($arr)
{
$cumArr=array();
$cum=0;
$size=sizeof($arr);
for($i=0;$i<$size;$i++)
{
$cum+=$arr[$i];
array_push($cumArr,$cum);
}
return $cumArr;
}
function weightedselect($frequency)
{
$arr=cumWghtArray($frequency);//array(35,96,100);
$len=sizeof($frequency);
$count=array();
$count[0]=$count[1]=$count[2]=0;
for($i=0;$i<MAX;$i++)
{
$r=mt_rand(0,$arr[$len-1]);
$index=binarysearch($arr,$r,0,$len-1);
$count[$index]++;
}
for($i=0;$i<3;$i++)
{
$count[$i]/=MAX;
echo $i." ".$count[$i]."\n";
}
}
function binarySearch($ar,$value,$first,$last)
{
if($last<$first)
return -1;
$mid=intVal(($first+$last)/2);
$a=$ar[$mid];
if($a===$value)
return $mid;
if($a>$value&&(($mid-1>=0&&$ar[$mid-1]<$value)||$mid==0))
return $mid;
else if($a>$value)
$last=$mid-1;
else if($a<$value)
$first=$mid+1;
return binarySearch($ar,$value,$first,$last);
}
Here is the Python Code. I have taken this code from this forum .
import random
import bisect
import collections
def cdf(weights):
total=sum(weights)
result=[]
cumsum=0
for w in weights:
cumsum+=w
result.append(cumsum/total)
return result
def choice(population,weights):
assert len(population) == len(weights)
cdf_vals=cdf(weights)
x=random.random()
idx=bisect.bisect(cdf_vals,x)
return population[idx]
weights=[0.30,0.40,0.30]
population="ABC"
counts={"A":0.0,"B":0.0,"C":0.0}
max=10000
for i in range(max):
c=choice(population,weights)
counts[c]=counts[c]+1
print(counts)
for k, v in counts.iteritems():
counts[k]=v/max
print(counts)
Problem is of mt_rand() function which is not uniform. The python random.rand() is very much uniform. Which random function should i implement in php with a proper seeding value every time it runs. I was thinking of using Withcmann (used by python random.random) but how will i provide the seed.
Both rand and mt_rand should both be more than sufficiently random for your task here. If you needed to seed mt_rand you could use mt_srand, but there's no need since PHP 4.2 as this is done for you.
I suspect the issue is with your code, which seems unnecessarily involved given what I believe you're trying to do, which is just pick a random number with weighted probabilities.
This may help: Generating random results by weight in PHP?

Categories