Forum Moderators: coopster

Message Too Old, No Replies

Find nearest real number

         

gosman

8:00 pm on Mar 11, 2010 (gmt 0)

10+ Year Member



I need a function to find the nearest real number.

I found the following code but it only allows for integers.

$match = 58;

$set = array(1,2,3,5,8,13,21,34,55,89,144,233,377,54);

foreach ($set as $fib)
{
$diff[$fib] = (int) abs($match - $fib);
}
$fibs = array_flip($diff);
$closest = $fibs[min($diff)];

echo $closest;

Any help really appreciated.

Readie

8:40 pm on Mar 11, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Are you trying to find the number defined in the array that is closest to $match?

If so:

$match = 58;

$set = array(1,2,3,5,8,13,21,34,55,89,144,233,377,54);

foreach($set as $fib){
if($fib <= $match) {
$num = ($match - $fib);
} else {
$num = ($fib - $match);
}
$new_set[$fib] = $num;
}

$val = min($new_set);
$key = array_search($val, $new_set);
echo $key;

gosman

10:49 am on Mar 12, 2010 (gmt 0)

10+ Year Member



Thanks Readie for you reply.

Your code works great if the numbers are integers, however in my real life scenario the number could be a float number.

See below

$match = 58.5;

$set = array(1,2,3,5,8,13,21,34,55,89,144,233,377,54,58.3);

foreach($set as $fib){
if($fib <= $match) {
$num = ($match - $fib);
} else {
$num = ($fib - $match);
}
$new_set[$fib] = $num;
}

$val = min($new_set);
$key = array_search($val, $new_set);
echo $key;

Any suggestions?

Readie

11:07 am on Mar 12, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you put quotes around floats it works fine, like:

$set = array(1,2,3,5,8,13,21,34,55,89,144,233,377,54,'59.3');

gosman

12:06 pm on Mar 12, 2010 (gmt 0)

10+ Year Member



Excellent.

Thank you Readie

Matthew1980

12:20 pm on Mar 12, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there,

When doing an array like that, you should put the quotes in anyway, at least thats my understanding of it, It will work without, but it's good coding practice to use the quotes. It's only when placing a $var in that you don't use quotes.

Cheers,

MRb