0

I'm trying to use (i), the sum of the sine values, as the basis for my if loop. The if loop needs to store the values of (d), for which sin(d*pi/180)+1 is equal to a fraction or multiple of (i), into the array arr. When I try to use i on the right side of the if statement, the code doesn't work properly, but if I try to constants, then the code works. I need a way to use variables, because I will not know ahead of time what I is going to be.

int arr[10];
//signed int d;
float i = 0;
int p;
float d;
float e;
//float s = sin(d*(PI/180))+1;//float produces decimals
void setup(){
  Serial.begin(9600);
}
void loop(){
  for(d = 0; d < 360; d++){
    i = i + sin(d*(PI/180))+1;//add each value to the previous one
  }
  Serial.println(i/360);//print the average of the values
    delay(500);  

  for(d = 0; d < 360; d++){
    if (sin(d*(PI/180))+1 == 1.5*i/360){
        arr[p++] = d;
      }
  }
  for(p = 0; p < 10; p++){
    Serial.println(arr[p]);
    delay(500);
  }

}

2
  • Can't catch your problem. What is working with constants and what is not working. "It did not work" is not enough to help ;) Commented Mar 13, 2019 at 8:25
  • If I use 1.5 instead of 1.5*i/360, in the if statement, the result is 1.00, 30, 150,0,0,0,0,0,0,0,0 (which is correct). But if I use 1.5*i/360, the result is 1.00,0,0,0,0,0,0,0,0,0,0. Commented Mar 13, 2019 at 14:21

1 Answer 1

2

The float values are stored in memory unlike we do that on paper. The floats are stored as powers of 2. So 0.5 or 0.25 can be stored precisely and 0.2 or 0.3 - cannot.

You are trying to compare the two floats (sin(d*(PI/180))+1 and 1.5*i/360. d in your case (though it is float) is actually represented as integer and is stored precisely and i is a float. So left and right sides can be approximately equal but are really equal (very) rarely. You can use a construction like this:

count fabs(arg1-arg2) and compare this result to required epsylon (some minor value that represents unsignifficant difference between the arguments).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.