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?

1
  • Why is 3 in the first example output but not in the second? Commented Aug 27, 2011 at 17:19

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

5 Comments

Dejavu: Why is 3 missing in output?^^
@Nobody: That was just a floating point error. I've updated my answer to fix that.
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)
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 ^^
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.