How to generate a range of floating-point numbers in PHP

1 Answer

0 votes
/*
 * ============================================================
 * Title: Reusable Floating-Point Range Generator in PHP
 * ============================================================
 *
 * PHP's built-in range() function is primarily intended for
 * integers and characters. While it can work with floats,
 * precision issues may occur when repeatedly adding step values.
 *
 * Best Practices:
 * - Validate all input parameters.
 * - Use strict typing.
 * - Avoid accumulating floating-point errors in loops.
 * - Calculate each value from its index.
 * - Return a reusable array of floating-point numbers.
 */

declare(strict_types=1);

/**
 * Generates a range of floating-point numbers.
 *
 * @param float $start Starting value (inclusive).
 * @param float $end Ending value (inclusive).
 * @param float $step Increment between values.
 *
 * @return array<float>
 */
function floatRange(float $start, float $end, float $step): array
{
    // Ensure the step size is valid.
    if ($step <= 0) {
        throw new InvalidArgumentException(
            'Step must be greater than zero.'
        );
    }

    // Determine how many values need to be generated.
    $numberOfSteps = (int) round(($end - $start) / $step);

    $result = [];

    // Generate each value from its index rather than
    // repeatedly adding the step value.
    for ($index = 0; $index <= $numberOfSteps; $index++) {
        $result[] = $start + ($index * $step);
    }

    return $result;
}

// ------------------------------------------------------------
// Example Usage
// ------------------------------------------------------------

$values = floatRange(
    start: 1.0,
    end: 2.0,
    step: 0.2
);

print_r($values);


/*
run:

Array
(
    [0] => 1
    [1] => 1.2
    [2] => 1.4
    [3] => 1.6
    [4] => 1.8
    [5] => 2
)

*/

 



answered Oct 7 by avibootz

Related questions

...