0

As part of a PHP project, I have the need of returning the sine value of each value included in an arbitrary interval. Moreover, I also need to be able to set the "scope" of the function, that is, how many decimal places I need to cycle.

Eg: 1 decimal place for interval 1 to 3 included: 1, 1.1, 1.2, ... 2.8, 2.9, 3

2 decimal places for the same interval

1, 1.01, 1.02 ... 2.98, 2.99, 3

Etc... I tried doing it with the "for" cycle, but it would only consider natural numbers.

Suggestions?

max0005
  • 210
  • 4
  • 9

1 Answers1

3

You can tweak the code below code to suit your needs:

$start = 1;
$end = 3;
$place = 1;

$step = 1 / pow(10, $place);

for($i = $start; $i <= $end; $i = round($i + $step, $place))
{
    echo $i . "\n";
}

Output:

1
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
2
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
3
  • Dejavu: Why is 3 missing in output?^^ – Nobody moving away from SE Aug 27 '11 at 17:24
  • @Nobody: That was just a floating point error. I've updated my answer to fix that. –  Aug 27 '11 at 17:29
  • Thank you so much, that worked perfectly!! Just one thing, when I raise the number of decimal places to 4-5 it gets extremely slow, is there any way I can make it faster? (I'm running localhost) – max0005 Aug 27 '11 at 17:52
  • 1
    It is in the nature of this, that it gets slower, when you create more values. I would say this already is the fastest approach you can get with php. If you want to be faster you probably need a faster language or a builtin function that maps to a faster language ^^ – Nobody moving away from SE Aug 27 '11 at 18:33
  • 1
    Actually, the bottleneck seems to be the output (I didn't check if that's the connection or the editor). Just the loop itself takes about a sec to run here for 5 decimals, but outputting those 200,000 lines and things really stall. – Inca Aug 27 '11 at 18:59