In: Computer Science
Modify your second order sequence code to test for oscillation. This can be done by calculating the difference between subsequent numbers in the sequence and observing whether the difference changes sign (ie: Do they swap from positive to negative or are they always positive or negative?). To complete this task will need to declare a “flag” variable. It can be of type int and have any name of your choosing. Given the initial values of x1 and x2 calculate the difference: x2 − x1. If it is positive, make the flag zero. If it is negative, make the flag one. You may assume that the difference will always be non-zero (ie: the initial values will never be equal). Each time a new entry in the sequence is generated re-calculate the value xn − xn−1. If, at any point, the sign of this calculation is different to the sign of x2 − x1 the program should print that the sequence oscillates and exit. If, after 20 iterations, no change of sign has been observed the program should print that no oscillation occurred and exita . Example 1: For the initial values x1 = 1, x2 = -0.5 and coefficients b1 = 0.2, b2 = 0.2 the sequence is: 1.00000 -0.50000 0.10000 -0.08000 0.00400 -0.01520 and the sequence oscillates (first difference is -1.5, then +0.6).
#include "stdio.h"
int main()
{
double b1=0.2,b2 =0.2,x1=1,x2=-0.5,x,d;
int n=2,flag;
d=x2-x1;
printf("%f\n%f\n",x1,x2);
while (n<5)
{
if(d<0){
flag=1;
} else if(d>0)
{
flag=0;
}
x=b1*x2+b2*x1;
printf("%f %f\n",x);
n++;
x1=x2;
x2=x;
}
return(0);
}
I cant do the difference sequence
Whole code:
#include <iostream>
using namespace std;
int main() {
float sequence[6]=
{1.00000,-0.50000,0.10000,-0.08000,0.00400,-0.01520};
int flag[5];
float difference[5];
int i=0;
for(i=0;i<5;i++)
{
difference[i]=sequence[i+1]-sequence[i];
}
cout<<"Sequential Difference: ";
for(i=0;i<5;i++)
{
cout<<difference[i]<<" ";
}
cout<<endl;
for(i=0;i<5;i++)
{
if(difference[i]<0)
{
flag[i]=1;
}
else
{
flag[i]=0;
}
}
cout<<"Flags: ";
for(i=0;i<5;i++)
{
cout<<flag[i]<<" ";
}
cout<<endl;
for(i=0;i<5;i++)
{
if(flag[i]!=flag[i+1])
{
cout<<"Sequential"<<endl;
break;
}
}
return 0;
}
For sequential difference I have used this part of code:
You just have to make a float array and then using for loop calculate the difference between the current value and next value and store this in a new float array.
For flags this part of code is used:
If the current value of difference in the difference array is negative then the current value of flag in flag array will be 1 otherwise 0.
For finding if the oscillation is sequential:
If the current value and the next value of flag in the flag array does not match then the oscillation is sequential.
If you run the code as a whole the output will be:
If you found this answer helpful, please give it a thumbs up! :)