I have the following PHP code in which I want to compare two decimal numbers. I have read in the PHP documentation that floating point numbers have limited precision.
$a = 0.0;
for ($i = 0; $i < 10; $i++) {
$a += 0.1;
}
var_dump($a);
echo gettype($a);
if ($a === 1.0) {
echo "IF";
} else {
echo "ELSE";
}
When I compare variable $a with 1.0, it always returns false, and the result will be 'ELSE'. My question is how I can get the code above working properly.
you can just do it this way:
//just a check if it is float, than round it to 1 decimal number and compare
if(is_float($a)){
echo 'not a float';
$a = round($a,1);
}
and output will be 'IF'
This question has been asked before, see Compare floats in PHP.
Basically you need to calculate the difference and see if it is small enough to be acceptable as "equal".
Try something like this:
$a = 0.0;
for ($i = 0; $i < 10; $i++) {
$a += 0.1;
$a=number_format($a,1);
//echo gettype($a);
//echo $a.'<br>';
if (floatval($a) === 1.0)
echo "IF";
else
echo "ELSE";
}
In order to make the comparison work I would truncate $a to one decimal place and format $a to a string with the required precision and compare it to "1.0".
To truncate $a I suggest reading this answer .
Or you can use $a as an integer. Them instead of incrementing by 0.1 use 1. And use 10 in the final comparison.
Related
In php, there is a built-in function strcmp to compare if two strings are same or not.
Returning value is integer number that if the first parameter is greater than the second I get > 0, if not < 0 and if the same 0.
So the part I don't get is comparing string as number.
Does PHP convert string to number and if so how's PHP converting?
$a = 'acorn';
$b = 'zebra';
var_dump( strcmp($a, $b) ); // -25 <- what's this number? seems like alphabetical position...nnn
Doesn't it really matter what number I get, shall I just take what it is?
Looking at the PHP: strcmp doc :
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
So yes, you can use it as it is to compare your string.
But if you want to understand the number returned by the function, it depend on the characters that makes the strings.
In ASCII :
A=65 < B=66 < C=67 ....
So if the string are different, one is gonna be greater than the other.
So you can also test it easily with a short script :
<?php
$a='A';
$b='B';
$c='C';
//Return -1 because $a is smaller than $b by one (65 < 66 )
echo strcmp($a,$b);
//Return -2 because $a is smaller than $c by two (65 < 67 )
echo strcmp($a,$c);
//Return -1 because $b is smaller than $c by one (66 < 67 )
echo strcmp($b,$c);
//Return 1 because $c is greater than $b by one (67 > 66 )
echo strcmp($c,$b);
//Return 2 because $c is greater than $a by two (67 > 65 )
echo strcmp($c,$a);
strcmp is using for comparing two strings in PHP.
If your result is greater the 0 its mean variable one ($a) is greater then Var2($b)
if return result is less then 0 its mean $b is greater and If result is equal to 0 its mean both strings are equal to each other.
$a="Hello world!";
$b= "Hello world!";
var_dump(strcmp($a, $b)); // result is 0
$a = "Hello";
$b = "Hello World";
var_dump(strcmp($a, $b)); // Outputs: -6
and If you want to see difference then you can use this
$a = 'some-content-here-example';
$b = 'some-content-example';
$asp = preg_split('//', $a, -1);
$bsp = preg_split('//', $b, -1);
$l1 = count($asp);
$l2 = count($bsp);
$length = $l1;
if ($l2 > $l1) {
$length = $l2;
}
$record = null;
$x = null;
for ($x = 0; $x < $length; $x++) {
if ($a[$x] != $b[$x]) {
if (!isset($a[$x])) {
$record.= $b[$x];
} else {
$record.= $a[$x];
}
}
}
echo $record;
I've been practicing a lot of algorithms recently for an interview. I was wondering if there was another way to solve this problem. I wrote it in a way where I only increment it positively, because I know from basic math that two negatives multiplied by each other would result to a positive number, so I would just have to make the integer that would satisfy the condition to negative.
Is there a way to write this elegantly where you didn't have the knowledge of multiplying two negative numbers result to a positive?
<?php
# Z = {integers}
# B = {x:x, x is an element of Z, x^2 + 1 = 10}
$numNotFound = true;
$x = 0;
$b = [];
while ($numNotFound) {
if ($x*$x + 1 == 10) {
array_push($b, $x, $x*-1);
$numNotFound = false;
}
$x++;
}
echo json_encode($b); #[3, -3]
Updated
This solution does not use the fact that -1 * -1 = 1. It will output the first number found as the first element in the array. If x=-3 then [-3,3] or if x=3 [3,-3].
$numNotFound = TRUE;
$x = 0;
$b = [];
Do{
if ((pow($x, 2) + 1) === 10) {
array_push($b, $x, 0 - $x);
$numNotFound = FALSE;
}
$x++;
}while($numNotFound);
echo json_encode($b); //[3, -3]
So I have a program in PHP, which draws three numbers from array, adds them up and checks if sum = 10. If yes, then it should print those numbers on the display.
What I want to do is to check which combination was drawn. For example:
First draw: 1+7+2
Second draw: 5+4+1
Third draw: 1+2+7
First and third had the same numbers, so third shouldn't be shown. Unfortunately, I have no idea how to do it.
My code:
<?PHP
$numb = array(1,2,3,4,5,6,7,8,9,0);
$hm = count($numb);
for ($a=0; $a<$hm;$a++)
for ($b=0; $b<$hm;$b++)
for ($c=0; $c<$hm;$c++)
{
$cnt = $numb[$a]+$numb[$b]+$numb[$c];
if ($cnt == 10)
{
print_r ($numb[$a]);
echo "+";
print_r ($numb[$b]);
echo "+";
print_r ($numb[$c]);
echo "<br>";
}
}
?>
With the provided code, you can simply draw numbers "in order" to avoid duplicates:
$numb = array(0,1,2,3,4,5,6,7,8,9); // <-- must be sorted from lowest to highest
for ($a = 0; $a < $hm; $a++)
for ($b = $a; $b < $hm; $b++) // <-- start from $a
for ($c = $b; $c < $hm; $c++) // <-- start from $b
Thus, the combination 1+2+7 is possible, but not 1+7+2, and also not 7+1+2 etc.
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.
I wrote a program in PHP to find the largest prime factor. I think it is quite optimized, because it loads quite fast. But, there is a problem: it doesn't count the prime factors of very big numbers. Here is the program:
function is_even($s) {
$sk_sum = 0;
for($i = 1; $i <= $s; $i++) {
if($s % $i == 0) { $sk_sum++; }
}
if($sk_sum == 2) {
return true;
}
}
$x = 600851475143; $i = 2; //x is number
while($i <= $x) {
if($x % $i == 0) {
if(is_even($i)) {
$sk = $i; $x = $x / $i;
}
}
$i++;
}
echo $sk;
The largest non-overflowing integer in PHP is stored in the constant PHP_INT_MAX.
You won't be able to work with integers larger than this value in PHP.
To see all of PHP's predefined constants, just use:
<?php
echo '<pre>';
print_r(get_defined_constants());
echo '</pre>';
?>
PHP_INT_MAX probably has a value of 2,147,483,647.
To handle numbers of arbitrary precision in PHP, see either the GMP or BC Math PHP extensions.
You should read about Prime testing and Sieving.
In particular, you don't need to test whether each of your divisors is prime.
Something like the following would be faster.
while($i <= $x)
{
while ($x % $i == 0)
{
$sk = $i;
$x = $x / $i;
}
$i++;
}
You can also stop your outer loop when $i reaches sqrt($x), and if you haven't found a divisor yet then you know $x is prime.
Well, every language has it's own (while usually same) limitations, so if you exceed this php's limit, you can't get any higher. Max Integer is 9E18.