public static function payback(array $values, float $rate = 0.0): float
    {
        $last_outflow = -1;
        for ($i = 0; $i < sizeof($values); $i++) {
            if ($values[$i] < 0) {
                $last_outflow = $i;
            }
        }

        if ($last_outflow < 0) {
            return 0.0;
        }

        $sum = $values[0];
        $payback_period = -1;
        for ($i = 1; $i < sizeof($values); $i++) {
            $prevsum = $sum;
            $discounted_flow = $values[$i] / (1 + $rate)**$i;
            $sum += $discounted_flow;
            if ($sum >= 0) {
                if ($i > $last_outflow) {
                    return ($i - 1) + (-$prevsum / $discounted_flow);
                }
                if ($payback_period == -1) {
                    $payback_period = ($i - 1) + (-$prevsum / $discounted_flow);
                }
            } else {
                $payback_period = -1;
            }
        }
        if ($sum >= 0) {
            return $payback_period;
        }
        return \NAN;
    }