Discussion about math, puzzles, games and fun. Useful symbols: ÷ × ½ √ ∞ ≠ ≤ ≥ ≈ ⇒ ± ∈ Δ θ ∴ ∑ ∫ π -¹ ² ³ °

You are not logged in.

- Topics: Active | Unanswered

Pages: **1**

**Paul****Member**- Registered: 2006-01-19
- Posts: 4

Yesterday I wrote asking the following

Hello

I have been trying to program some sine equations.

My hope has been to create a loop of 100 iterations to generate results from 0 to 1 which has been successful

I have started with i set to 0

I have incremented it by Pi/200 stopping when i gets to Pi/2

And sin(i) has produced 0 to 1 as hoped for.

The problem is how do I generate 0 to 1 to 0 again

I have tried stopping i when it gets to pi which works very well until the final loop where I get a tiny value. Can anyone help. Am i trying the impossible?

--------------------------

I was asked to supply the code. Here it is

It works great but the last value I get is

Sin = 1.12246908816338e-14

when I was hoping for 0

maybe it is just a rounding problem as suggested

---code---------------

//100 loops to produce sin results from 0 to 1;

//trace() outputs to screen

var loopCount=0;

var desiredLoops=100;

for (var i:Number=0;i<=Math.PI;i+= Math.PI/(desiredLoops*2)){

trace("loopCount = "+loopCount);

trace("Sin = "+Math.sin(i));

loopCount++;

}

------------------------

One further question

How could I modify the code to produce

-1 to 0 to 1 to 0 to -1

Offline

**MathsIsFun****Administrator**- Registered: 2005-01-21
- Posts: 7,636

OK, that makes sense. You are incrementing a real number (one with fractional component), and the computer can't do that with total accuracy. However adding integers will be accurate. so:

```
for (var i=0;i<desiredLoops;i++) {
r=(i/desiredLoops)*Math.PI;
trace("Sin = "+Math.sin(r));
}
```

I haven't included data types. "i" and "desiredLoops" should be integers, "r" a real, and you will need to be careful with "i/desiredLoops" to make sure it creates a fractional result (ie convert both to a real value before dividing).

As to the question of rising and falling values - the sin function does that anyway, so just go to higher values, something like:

r = (i/desiredLoops)*Math.PI*4; // times 4

And you can make it start at a lower value by having something like:

r = ( (i/desiredLoops) - 0.5 )*Math.PI*4;

Play with it! Use trace() a lot, and let us know what happens:)

"The physicists defer only to mathematicians, and the mathematicians defer only to God ..." - Leon M. Lederman

Offline

Pages: **1**