ASP classic CLng function - convert to PHP - php

I have an old site created with ASP classic and now I got up the courage to convert it to PHP. Must say I am NOT an expert in neither of this languages.
There is a simple function that is driving me crazy. It uses CLng in a way I never seen before and I can't find a similar method in PHP.
Here is the function in ASP classic:
Function TransferDecode(ByRef Source)
Dim C, I, P, S, K
C = Len(Source) / 2
TransferDecode = ""
For I = 0 to C - 1
P = I * 2 + 1
S = Mid(Source, P, 2)
K = CLng("&H" & S)
TransferDecode = TransferDecode & Chr(K)
Next
End Function
And here is my (uncessefull) attempt to convert to PHP:
function transferDecode($source) {
$r = '';
$c = strlen($source) / 2;
for ($i = 0; $i <= $c - 1; $i++) {
$p = $i * 2 + 1;
$s = substr($source, $p, 2);
$k = '&H'.$s;
$r .= chr((int)$k);
}
return $r;
}
Please, can someone explain me what "CLng("&H" & S)" do? Is there a similar CLng method in PHP?
Thank you!

I'd try something like that:
$r .= chr(intval($s, 16));
note: variable $k is not used at all
also, strings in vbscript are 1-based, while in php are 0-based, so $p should be calculated as $p = $i * 2;

Related

Iterations in VBA - Comparable method in PHP

Using VBA code I found in a spreadsheet to adapt to an online PHP application. The code uses the bisection method in mathematics to find optimal value for a calculation required to price options.
Upper = estimate_upper
Lower = estimate_lower
UUpper = container
Start_Iteration:
IterationCountE = 0.000000001
While (Upper - Lower) > IterationCountE
Mid = (Upper + Lower) / 2
c1 = calculations1...
c2 = calculations2...
If (c2 - c1) > 0 Then
Lower = Mid
Else
Upper = MId
End If
Wend 'Ends the while loop
If (Round(Mid, 4) = Round(UUpper, 4)) Then
Upper = 2 * UUpper
UUpper = Upper
GoTo Start_Iteration
End If
Function = Mid
For most part, I understand the mechanics of the iteration. My attempted PHP conversion is as follows:
$IterationCountE = 0.00000000001;
while ( ($Upper - $Lower) > $IterationCountE ) {
$Mid = ($Upper + $Lower) / 2;
$c1 = calculation1();
$c2 = calculation2();
if ( ($c2 - $c1) > 0 ) {
$Lower = $Mid;
} else {
$Upper = $Mid;
}
if (round($Mid, 4) == round($UUpper, 4)) {
$Upper = 2 * $UUpper;
$UUpper = $Upper;
}
}
return $Mid;
Is this the best way to approach an similar iteration in PHP? Would it be better to wrap the iteration in a function and refer back to it like in the VBA code?
I do not get the same value results when comparing the PHP output to the value from a macro.

Bailey-Borwein-Plouffe in php trouble

I am trying to implement the BBP algorithm in php. My code is returning a decimal which i thought was odd as it should be in hex. I was told to convert to decimal from hex by multiplying by 16 also but now its all just wrong. Here is a sample:
$n1=$n2=$n3=$n4=$n5=$n6=$n7=$n8 =0;
$S1=$S2=$S3=$S4=$S5=$S6=$S7=$S8 = 0; //initializing
$k = 0;
$m1= 8*$k + 1;
$m2 = 8*$k + 4;
$m3 = 8*$k + 5;
$m4 = 8*$k = 6;
$b =16;
$e=$n-$k;
while($k<$n){ //Sum 1 of 8
$S1 +=Modular($b, $m1, $e)/$m1; //see Moduler_Expansion.php
$k++;
}
$k = $n +1; //redefine for second sum, and every other
while($k<$limit){ //Sum 2 of 8
$S2 += (pow($b,$n-$k))/($m1);
$k++; //now repeat similar process for each sum.
}
and I repeat the process for each term of BBP then:
$S = 4*($S1 + $S2) - 2*($S3+$S4) -($S5+$S6) - ($S7+$S8);
`
Following the wiki page I then strip the integer and multiply by 16, but for $k =0 I get; 3.4977777777778
and for $k = 1: 7.9644444444448.
I dont think these are right, it could just be i do not know how to interpret th ouput properly. Can anyone offer any advice?

How to generate random numbers to produce a non-standard distributionin PHP

I've searched through a number of similar questions, but unfortunately I haven't been able to find an answer to this problem. I hope someone can point me in the right direction.
I need to come up with a PHP function which will produce a random number within a set range and mean. The range, in my case, will always be 1 to 100. The mean could be anything within the range.
For example...
r = f(x)
where...
r = the resulting random number
x = the mean
...running this function in a loop should produce random values where the average of the resulting values should be very close to x. (The more times we loop the closer we get to x)
Running the function in a loop, assuming x = 10, should produce a curve similar to this:
+
+ +
+ +
+ +
+ +
Where the curve starts at 1, peeks at 10, and ends at 100.
Unfortunately, I'm not well versed in statistics. Perhaps someone can help me word this problem correctly to find a solution?
interesting question. I'll sum it up:
We need a funcion f(x)
f returns an integer
if we run f a million times the average of the integer is x(or very close at least)
I am sure there are several approaches, but this uses the binomial distribution: http://en.wikipedia.org/wiki/Binomial_distribution
Here is the code:
function f($x){
$min = 0;
$max = 100;
$curve = 1.1;
$mean = $x;
$precision = 5; //higher is more precise but slower
$dist = array();
$lastval = $precision;
$belowsize = $mean-$min;
$abovesize = $max-$mean;
$belowfactor = pow(pow($curve,50),1/$belowsize);
$left = 0;
for($i = $min; $i< $mean; $i++){
$dist[$i] = round($lastval*$belowfactor);
$lastval = $lastval*$belowfactor;
$left += $dist[$i];
}
$dist[$mean] = round($lastval*$belowfactor);
$abovefactor = pow($left,1/$abovesize);
for($i = $mean+1; $i <= $max; $i++){
$dist[$i] = round($left-$left/$abovefactor);
$left = $left/$abovefactor;
}
$map = array();
foreach ($dist as $int => $quantity) {
for ($x = 0; $x < $quantity; $x++) {
$map[] = $int;
}
}
shuffle($map);
return current($map);
}
You can test it out like this(worked for me):
$results = array();
for($i = 0;$i<100;$i++){
$results[] = f(20);
}
$average = array_sum($results) / count($results);
echo $average;
It gives a distribution curve that looks like this:
I'm not sure if I got what you mean, even if I didn't this is still a pretty neat snippet:
<?php
function array_avg($array) { // Returns the average (mean) of the numbers in an array
return array_sum($array)/count($array);
}
function randomFromMean($x, $min = 1, $max = 100, $leniency = 3) {
/*
$x The number that you want to get close to
$min The minimum number in the range
$max Self-explanatory
$leniency How far off of $x can the result be
*/
$res = [mt_rand($min,$max)];
while (true) {
$res_avg = array_avg($res);
if ($res_avg >= ($x - $leniency) && $res_avg <= ($x + $leniency)) {
return $res;
break;
}
else if ($res_avg > $x && $res_avg < $max) {
array_push($res,mt_rand($min, $x));
}
else if ($res_avg > $min && $res_avg < $x) {
array_push($res, mt_rand($x,$max));
}
}
}
$res = randomFromMean(22); // This function returns an array of random numbers that have a mean close to the first param.
?>
If you then var_dump($res), You get something like this:
array (size=4)
0 => int 18
1 => int 54
2 => int 22
3 => int 4
EDIT: Using a low value for $leniency (like 1 or 2) will result in huge arrays, since testing, I recommend a leniency of around 3.

Convert septet to octet in php

I need to convert septets to octest like this c example:
private void septetToOctet()
{
int len = 1;
int j = 0;
int septetcount = septet.Count;
while (j < septet.Count - 1)
{
string tmp = septet[j]; // storing jth value
string tmp1 = septet[j + 1]; //storing j+1 th value
string mid = SWAP(tmp1);
tmp1 = mid;
tmp1 = tmp1.Substring(0, len);
string add = SWAP(tmp1);
tmp = add + tmp;// +"-";
tmp = tmp.Substring(0, 8);
//txtoctet.Text += tmp + " || ";
octet.Add(tmp);
len++;
if (len == 8)
{
len = 1;
j = j + 1;
}
j = j + 1;
}
}
..only problem is - i need to do it in php. Does anybody have an code example for this ?
Most of the code can be translated to PHP with little changes. For instance, the first two assignments would be just $len = 1 and $j = 0. There is no strong static typing in PHP.
Since numbers and strings are scalars in PHP, you cannot call methods on them, so you cannot do tmp1.substring but would have to do substr($tmp1, …).
septet and octet would be arrays in PHP. Again, there is no methods on arrays in PHP. To add to an array, you simply do $octet[] = $tmp. To count the elements you do count($septet).
There is no SWAP in PHP, but you can derive the rather trivial function from Is there a built in swap function in C?
These hints should get you closer to a working implementation.

PHP equivalent to Javascript "with" scope statement

Porting some code from Javascript i'm having this incovenience. For example:
In javascript we can produce this code.
var a, x, y;
var r = 10;
with (Math) {
a = PI * r * r;
x = r * cos(PI);
y = r * sin(PI / 2);
}
Instead
a = Math.PI * r * r;
x = r * Math.cos(Math.PI);
y = r * Math.sin(Math.PI / 2);
In this last example will be the same comportament in PHP, IE, in second code example Math is redundant.
Someone have any solution for a clear an elegant code?
I'm adding the following code as new example:
class MyExampleClass {
function example {
for($i = 0; $i < count($this->Registers); $i++) {
$r = "50";
$r .= $this->ZeroFill($this->numericOnly($this->Registers[$i]->Id)), 15) . $this->ZeroFill($this->numericOnly($this->Registers[$i]->Inscription), 25);
$r .= $this->ZeroFill($this->Registers[$i]->Model, 2 );
$r .= $this->PadR($this->alpha($this->Registers[$i]->Date), 10 );
$this->WriteRecord( $r);
}
}
In third example I can use a temp $var inside for statement for $this->Registers[$i], but if all treatment code are became in a class like class Sanitize.
with (Sanitize) {
$r .= ZeroFill(numericOnly($tmp), 15); // are much more clear and using OO
}
I want an way to do an shorter and no repetitive code.
What you are looking for is more akin to java than javascript, in java this qualification is optional and can be left out. The javascript's with statement is half functional as it doesn't even work with assignments.
PHP doesn't have that and you have to explicitly type out $this-> every time.
PHP scopes are very different than Javascript. I suppose the best I could think of is extend a class and using $this-> rather than the class name everywhere - Do you have a use case you could share with us?
pi(), cos(), & sin() are all reserved functions in PHP
<?php
$r = 10;
$a = pi() * $r * $r;
$x = $r * cos(pi());
$y = $r * sin(pi() / 2);
?>

Categories