简体   繁体   中英

Why does this C++ function produce chaotic output?

I have the following code:

int main ( int argc, char **argv ){
double lambda = 4;
double x = .2;

for ( int i=1; i<=30; i++ )
  {
    printf( "%.5f \n", x );
    x = lambda * x * (1-x);
  }           
}

That outputs the following:

0.20000 0.64000 0.92160 0.28901 0.82194 0.58542 0.97081 0.11334 0.40197 0.96156 0.14784 0.50392 0.99994 0.00025 0.00098 0.00394 0.01568 0.06174 0.23173 0.71212 0.82001 0.59036 0.96734 0.12638 0.44165 0.98638 0.05374 0.20342 0.64815 0.91221

My question is: What is the most apt algorithmic/mathematical description for the manner in which 'x' is being manipulated every iteration?

For each iteration of the loop, the variable x is assigned a new value based on some calculation involving the old value of x . The variable i is used simply to limit the number of times this calculation repeats.

Similarly, you can change the value of x (without using i ) in a much simpler way:

x = x + 1;

Use that instead of the x = lambda * x * (1-x); line and observe how the value increases.

You are using x in the following statement x = lambda * x * (1-x); . This way x value changes on every iteration.

The "i" in the for loop is known as the iteration variable, which means it will be used as a counter for keeping track of the no. of iterations of the loop.

Whereas, the "x" is the variable which you want to play with in the loop.

You can try printing both the values of i and x in the loop to understand the concepts of iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM