Skip to main content

The Butterfly Effect: Chaos in Two Simple Machines

Chaos computed in R: the Lorenz system, whose path draws a butterfly in 3D (plotly), and 100 double pendulums whose starts differ by a thousandth of a degree, which swing together for a few seconds and then scatter (a GIF made with ggplot2 and magick). How fast tiny differences grow, why a gentle swing is not chaotic, and why a forecast gains so little from a more precise start.

What is this?

Some machines follow exact rules, with nothing left to chance, and still cannot be predicted for long: a difference too small to measure at the start grows until it is as large as the motion itself. This is chaos, and its best-known picture is the butterfly effect. This page computes two such machines in R and watches tiny differences grow. Five questions:

  1. What shape does the Lorenz system draw?
  2. How fast do two almost identical starts part?
  3. What do 100 double pendulums do?
  4. Is a double pendulum always chaotic?
  5. Why does a more precise start buy so little time?

Nothing is downloaded: every number and every picture is computed on the page from the equations of the two machines.

  • The Lorenz system is three equations that Edward Lorenz, a meteorologist at MIT, cut down from a model of a layer of air heated from below, like water in a pot on a stove (Lorenz 1963). Its three numbers stand for the air: x for how fast it turns over, y for the difference in temperature between the rising and the sinking air, and z for how far the temperature from the bottom to the top departs from a straight line.
  • The double pendulum is a pendulum that hangs from the end of another: two stiff arms of 1 m, each with a weight of 1 kg at its end, swinging in one plane, without friction (Levien and Tan 1993).

The words of this page:

  • deterministic: the future follows from the present by fixed rules. Started twice from exactly the same point, a deterministic machine does exactly the same thing twice;
  • the state of a machine: the numbers that fix it at one moment. For the Lorenz system they are x, y and z; for a double pendulum, the angle of each arm from hanging straight down and how fast it turns;
  • chaos: deterministic motion that never repeats itself, and in which any tiny difference of the start grows quickly, by doubling again and again, until the two motions have nothing in common. This is sensitive dependence on initial conditions; it is called the butterfly effect after a talk that Lorenz gave in 1972, “Predictability: does the flap of a butterfly’s wings in Brazil set off a tornado in Texas?”;
  • an attractor: the shape that the motion settles onto and keeps going round, whatever its start. The attractor of the Lorenz system looks like a butterfly;
  • exponential growth and the Lyapunov exponent, λ (lambda): a gap that grows exponentially takes always the same time to double. λ measures how fast: the gap is multiplied by e (2.718) every 1/λ, doubles every ln 2/λ = 0.69/λ, and grows ten-fold every ln 10/λ = 2.30/λ;
  • time units: the Lorenz system’s time has no unit of its own, because its equations are scaled; the pendulums’ time is in seconds;
  • the Runge–Kutta method (RK4): the computer moves each machine on in small steps, each time looking at how fast its state changes at the start, in the middle and at the end of the step: steps of 0.005 time units for the Lorenz system and of a thousandth of a second for the pendulums.

Packages

Code
# install.packages(c("plotly","ggplot2","magick","ragg"))
library(plotly)
library(ggplot2)
library(magick)
Code
# short labels of numbers for the text
number<-function(x) {
  result<-format(round(x),big.mark=",",trim=TRUE,scientific=FALSE)
  return(result)
}
# to one or two decimals, with a minus sign rather than a hyphen: "−18.7"
one<-function(x) {
  result<-sub("^-","−",format(round(x,1),nsmall=1,trim=TRUE))
  return(result)
}
two<-function(x) {
  result<-sub("^-","−",format(round(x,2),nsmall=2,trim=TRUE))
  return(result)
}
percent<-function(x) {
  result<-paste0(round(x),"%")
  return(result)
}

The machines

One step at a time

Code
# one step of the Runge–Kutta method (RK4): the rate of change is taken at the start of the step,
# twice halfway and at its end, and the four are averaged. Each row of the matrix s is one copy of a
# machine, so that many copies move on together
rk4_step<-function(s,dt,rate) {
  k1<-rate(s)
  k2<-rate(s+dt/2*k1)
  k3<-rate(s+dt/2*k2)
  k4<-rate(s+dt*k3)
  result<-s+dt/6*(k1+2*k2+2*k3+k4)
  return(result)
}

The Lorenz system

Lorenz’s three equations say how fast x, y and z change at each moment: dx/dt = σ(y − x), dy/dt = x(ρ − z) − y and dz/dt = xy − βz, with σ = 10, ρ = 28 and β = 8/3, the values that he used. Every run on this page starts from the same point of the attractor: from x = y = z = 1, the system is moved on for 20 time units, by which time it has settled onto the butterfly.

Code
sigma<-10
rho<-28
beta<-8/3
lorenz_rate<-function(s) {
  result<-cbind(sigma*(s[,2]-s[,1]),
                s[,1]*(rho-s[,3])-s[,2],
                s[,1]*s[,2]-beta*s[,3])
  return(result)
}
# copies of the system (one to a row of start) moved on together for a time, in steps of 0.005 time
# units; the state of every copy is kept every `keep` steps, as an array of time × copy × (x, y, z)
lorenz_dt<-0.005
lorenz_run<-function(start,time,keep=2) {
  s<-start
  steps<-round(time/lorenz_dt)
  result<-array(NA_real_,c(steps%/%keep+1,nrow(s),3))
  result[1,,]<-s
  for(k in seq_len(steps)) {
    s<-rk4_step(s,lorenz_dt,lorenz_rate)
    if(k%%keep==0)
      result[k%/%keep+1,,]<-s
  }
  return(result)
}
# the start of every run: x = y = z = 1, moved on for 20 time units
start<-matrix(lorenz_run(matrix(1,1,3),20,keep=round(20/lorenz_dt))[2,1,],nrow=1)

The double pendulum

The equations of the double pendulum follow from Newton’s laws for two arms of the same length with the same weight at their ends (Levien and Tan 1993). Each run moves 100 pendulums on together: their arms start still, the upper arms at the same angle and the lower arms 0.001° apart from one pendulum to the next, so that the 100 lower arms span 0.099°.

Code
# the state of a pendulum: the angle of each arm from hanging straight down (theta1 for the upper
# arm, theta2 for the lower one, in radians) and how fast each turns (omega1 and omega2, radians a
# second); arms of 1 m with 1 kg at their ends, and g = 9.81 m/s²
g<-9.81
pendulum_rate<-function(s) {
  d<-s[,1]-s[,2]
  under<-3-cos(2*d)
  turn1<-(-3*g*sin(s[,1])-g*sin(s[,1]-2*s[,2])-2*sin(d)*(s[,4]^2+s[,3]^2*cos(d)))/under
  turn2<-2*sin(d)*(2*s[,3]^2+2*g*cos(s[,1])+s[,4]^2*cos(d))/under
  result<-cbind(s[,3],s[,4],turn1,turn2)
  return(result)
}
# the energy of a pendulum, in joules more than it has hanging still; without friction it stays the
# same, which checks the computation
pendulum_energy<-function(s) {
  result<-s[,3]^2+s[,4]^2/2+s[,3]*s[,4]*cos(s[,1]-s[,2])-2*g*cos(s[,1])-g*cos(s[,2])+3*g
  return(result)
}
# 100 pendulums, both arms at the same angle (in degrees) and the lower arms 0.001° apart, moved on
# for 30 seconds in steps of a thousandth of a second; their states are kept every hundredth of a
# second, as an array of time × pendulum × (theta1, theta2, omega1, omega2)
pendulum_run<-function(angle,n=100,apart=0.001,seconds=30,dt=0.001,keep=10) {
  s<-cbind(angle*pi/180,(angle+(seq_len(n)-1)*apart)*pi/180,0,0)
  steps<-round(seconds/dt)
  result<-array(NA_real_,c(steps%/%keep+1,n,4))
  result[1,,]<-s
  for(k in seq_len(steps)) {
    s<-rk4_step(s,dt,pendulum_rate)
    if(k%%keep==0)
      result[k%/%keep+1,,]<-s
  }
  return(result)
}
gentle_angle<-20
wild_angle<-120
gentle<-pendulum_run(gentle_angle)
wild<-pendulum_run(wild_angle)
pendulum_time<-(seq_len(dim(wild)[1])-1)*0.01
# where the weight at the end of each lower arm is: x to the right and y up, in meters from the
# pivot
tip<-function(s) {
  result<-cbind(sin(s[,1])+sin(s[,2]),-cos(s[,1])-cos(s[,2]))
  return(result)
}
# how far apart the 100 pendulums are at each moment: the largest distance between the ends of the
# lower arms of any two of them, in meters
spread<-function(run) {
  result<-apply(run,1,function(s) max(dist(tip(s))))
  return(result)
}

Charts

Code
dark_gray<-"#6b6b6b" # also the color of the notes
reference_gray<-"#a3a3a3" # the dashed lines that compare a series with a rule
ink<-"#191919"
# the colors of the series, told apart also by color-blind readers (each pair checked)
blue<-"#257de0"
orange<-"#f47230"
green<-"#00b894"

# the source of a chart, as a note under it, and the common layout; note_shift moves the note down
# by a number of pixels, which stays the same however tall the plot is
chart<-function(p,title,source,y_title="",x_title="",y_axis=list(),x_axis=list(),
                annotations=list(),margin=list(t=70,b=90),note_y=-0.16,note_shift=0,...) {
  note<-list(text=paste("Source:",source),xref="paper",yref="paper",x=0,y=note_y,xanchor="left",
             yanchor="top",yshift=note_shift,align="left",showarrow=FALSE,
             font=list(size=11,color=dark_gray))
  result<-layout(p,
                 title=list(text=title,x=0.02,xanchor="left",y=0.97,yanchor="top"),
                 margin=margin,
                 annotations=c(annotations,list(note)),
                 ...)
  if(nchar(paste0(y_title,x_title))>0||length(c(y_axis,x_axis))>0)
    result<-layout(result,yaxis=modifyList(list(title=y_title),y_axis),
                   xaxis=modifyList(list(title=x_title),x_axis))
  result<-config(result,displaylogo=FALSE)
  return(result)
}
legend_top<-list(orientation="h",x=0,y=1.02,yanchor="bottom",itemsizing="constant")
computed<-"computed on this page"
lorenz_source<-paste0(computed," from Lorenz's equations (1963), with σ = 10, ρ = 28, β = 8/3.")
pendulum_source<-paste(computed,"for frictionless double pendulums: arms of 1 m, weights of 1 kg.")

# a 3D chart is built once and its second copy of every number ("attrs") dropped, which halves its
# size; the path is drawn in hundredths as whole numbers, because plotly for R writes any other
# number with 17 digits (8.49 as 8.4900000000000002). The axes are hidden
finish_3d<-function(p) {
  result<-plotly_build(p)
  result$x$attrs<-NULL
  return(result)
}
# buttons under the 3D chart that turn it to three views
views<-list(Wings=list(eye=list(x=0,y=-2.2,z=0.1),up=list(x=0,y=0,z=1)),
            `From above`=list(eye=list(x=0,y=0,z=2.4),up=list(x=0,y=1,z=0)),
            `From the side`=list(eye=list(x=2.2,y=0,z=0.1),up=list(x=0,y=0,z=1)))
view_buttons<-lapply(names(views),function(v)
  list(label=v,method="relayout",args=list(list(scene.camera=c(views[[v]],
                                                                list(center=list(x=0,y=0,z=0)))))))
view_menu<-list(type="buttons",direction="right",x=0,y=0,xanchor="left",yanchor="top",
                showactive=FALSE,buttons=view_buttons)

The movie of the pendulums

Code
# each pendulum in a shade of blue, from light (its lower arm started at 20° or 120°) to dark
# (0.099° more). 20 shades, each shared by 5 neighboring pendulums, keep the GIF small
ramp<-c("#84b9f3","#6aabf1","#519ced","#338ced","#257de0","#2370cd","#1b64be","#1757ac","#0f4a96",
        "#0e3d7e")
shades<-20
pendulum_colours<-colorRampPalette(ramp)(shades)[ceiling(seq_len(100)*shades/100)]
# the arms of the pendulums at one moment, as segments, the upper arm and then the lower arm of
# each; shift moves the pivot to the right, in meters
arm_segments<-function(s,shift) {
  elbow<-cbind(sin(s[,1]),-cos(s[,1]))
  end<-tip(s)
  n<-nrow(s)
  result<-data.frame(x=shift+c(rep(0,n),elbow[,1]),
                     y=c(rep(0,n),elbow[,2]),
                     xend=shift+c(elbow[,1],end[,1]),
                     yend=c(elbow[,2],end[,2]),
                     colour=rep(pendulum_colours,2),
                     pendulum=rep(seq_len(n),2))
  return(result)
}
# a frame: the gentle pendulums on the left, the wild ones on the right, the time at the bottom
shift<-4.6
panel_titles<-paste0(c("Gentle: both arms at ","Wild: both arms at "),
                     c(gentle_angle,wild_angle),"°")
frame_plot<-function(k) {
  arms<-rbind(arm_segments(gentle[k,,],0),arm_segments(wild[k,,],shift))
  arms<-arms[order(arms$pendulum),]
  result<-ggplot(arms)+
    geom_segment(aes(x,y,xend=xend,yend=yend,colour=colour),linewidth=0.35)+
    geom_point(aes(xend,yend,colour=colour),size=0.8)+
    annotate("point",x=c(0,shift),y=0,size=1.6,colour=ink)+
    annotate("text",x=c(0,shift),y=2.3,label=panel_titles,size=3.8,colour=ink,fontface="bold")+
    annotate("text",x=shift/2,y=-2.35,label=sprintf("%.1f s",pendulum_time[k]),size=3.8,
             colour=dark_gray)+
    scale_colour_identity()+
    coord_fixed(xlim=c(-2.2,shift+2.2),ylim=c(-2.5,2.5),expand=FALSE)+
    theme_void()+
    theme(plot.background=element_rect(fill="#ffffff",colour=NA))
  return(result)
}
# the movie: a frame every 0.08 seconds of the first 18, drawn by ggplot into png files (ragg) and
# put by magick on one palette (the blues, the inks and 24 grays, without dithering), then written
# as a GIF that plays in real time, loops and holds its last frame for about a second
movie<-function(file,seconds=18,every=8,hold=12) {
  moments<-seq(1,round(seconds/0.01)+1,by=every)
  frames<-file.path(tempdir(),sprintf("pendulums_%03d.png",seq_along(moments)))
  on.exit(unlink(frames))
  for(k in seq_along(moments)) {
    ragg::agg_png(frames[k],width=640,height=356,res=85,background="#ffffff")
    # the png file is closed even if a frame fails, so that later plots do not go into it
    tryCatch(print(frame_plot(moments[k])),finally=dev.off())
  }
  level<-round(seq(0,255,length.out=24))
  colours<-unique(c(pendulum_colours,"#ffffff",ink,dark_gray,rgb(level,level,level,
                                                                  maxColorValue=255)))
  palette<-image_read(as.raster(matrix(colours,nrow=1)))
  images<-image_read(c(frames,rep(frames[length(frames)],hold)))
  gif<-image_animate(image_map(images,palette,dither=FALSE),delay=every,optimize=TRUE)
  image_write(gif,file)
  return(file)
}
# the file of the movie: in the folder of the page's figures when the page is rendered, so that it
# is published with them, or a temporary file when the code is run by hand
gif_file<-function() {
  result<-if(isTRUE(getOption("knitr.in.progress"))) knitr::fig_path(".gif") else
    tempfile(fileext=".gif")
  dir.create(dirname(result),recursive=TRUE,showWarnings=FALSE)
  return(result)
}

1. What shape does the Lorenz system draw?

Code
path<-as.data.frame(lorenz_run(start,100)[,1,])
names(path)<-c("x","y","z")
path$time<-(seq_len(nrow(path))-1)*2*lorenz_dt
# a loop is one turn round one of the two holes; the path passes the top of a loop where z is
# highest. The side of each loop is the sign of x at its top
tops<-which(diff(sign(diff(path$z)))<0)+1
side<-ifelse(path$x[tops]<0,"left","right")
stays<-rle(side)
switches<-length(stays$lengths)-1
# the centers of the two holes: the two states, other than 0, 0, 0, where nothing changes
hole<-sqrt(beta*(rho-1))

A butterfly, whose two wings the path visits in no set order. In 100 time units the path goes round 134 loops. Each loop circles one of two holes, at x = y = −8.49 or +8.49 and z = 27: the two states, besides 0, 0, 0, at which nothing would change. But they are unstable, like a pencil standing on its point: the path spirals out from one of them, a little further with every loop, until it is thrown over to the other. It switched wings 54 times, stayed for 11 loops at most on one wing and for 2.4 on average, and spent 51% of its loops on the left. It never leaves its box (x from −18.7 to 17.9, y from −25.4 to 23.9, z from 3.8 to 46.0), and it never comes back exactly to where it was: Lorenz called such motion nonperiodic. It goes round and round, never twice the same way.

Code
curve<-data.frame(x=round(100*path$x),y=round(100*path$y),z=round(100*path$z))
wing_scale<-list(list(0,blue),list(0.5,blue),list(0.5,green),list(1,green))
centres<-data.frame(x=round(100*c(-hole,hole)),y=round(100*c(-hole,hole)),z=round(100*(rho-1)),
                    name=c("Left wing (x below 0)","Right wing (x above 0)"),
                    colour=c(blue,green),
                    sign=c("−","+"))
p<-plot_ly(curve,x=~x,y=~y,z=~z,type="scatter3d",mode="lines",
           line=list(color=as.numeric(path$x>0),colorscale=wing_scale,cmin=0,cmax=1,width=3),
           hoverinfo="skip",showlegend=FALSE)
for(k in 1:2)
  p<-add_trace(p,data=centres[k,],x=~x,y=~y,z=~z,type="scatter3d",mode="markers",
               name=centres$name[k],inherit=FALSE,
               marker=list(color=centres$colour[k],size=7,line=list(color="#ffffff",width=2)),
               hovertemplate=paste0("<b>Centre of the ",tolower(sub(" \\(.*","",centres$name[k])),
                                    "</b><br>x = y = ",centres$sign[k],two(hole),", z = ",
                                    number(rho-1),"<br>the path circles it but never ",
                                    "reaches it<extra></extra>"))
p %>%
  chart("The path of the Lorenz system, 100 time units",
        paste(lorenz_source,"Drag to turn, scroll to zoom."),
        margin=list(t=100,b=80,l=0,r=0),note_y=0,note_shift=-40,legend=legend_top,
        scene=list(xaxis=list(visible=FALSE),yaxis=list(visible=FALSE),zaxis=list(visible=FALSE),
                   aspectmode="data",dragmode="turntable",
                   camera=list(eye=list(x=0.5,y=-2,z=0.5))),
        updatemenus=list(view_menu)) %>%
  finish_3d()

The color shows the wing: blue where x is below 0, green where it is above. Turned From above, the two wings make a figure of eight; From the side, they lie one behind the other, each a round disc of loops around its center.


2. How fast do two almost identical starts part?

Code
# two runs from the same start, the second 0.00000001 further along x
nudge<-1e-8
pair<-lorenz_run(rbind(start,start+c(nudge,0,0)),40)
runs<-data.frame(time=(seq_len(dim(pair)[1])-1)*2*lorenz_dt,first=pair[,1,1],second=pair[,2,1])
runs$gap<-sqrt(rowSums((pair[,1,]-pair[,2,])^2))
apart<-runs$time[which(runs$gap>1)[1]]
# the typical distance between two points of the butterfly: the mean distance between 2,000 pairs of
# points of the path of question 1, chosen at random
set.seed(1)
first_points<-as.matrix(path[sample(nrow(path),2000,replace=TRUE),c("x","y","z")])
second_points<-as.matrix(path[sample(nrow(path),2000,replace=TRUE),c("x","y","z")])
typical<-mean(sqrt(rowSums((first_points-second_points)^2)))
unrelated<-runs$time[which(runs$gap>typical)[1]]
# the Lyapunov exponent: two copies 0.00000001 apart are moved on for 500 time units; every 0.1 time
# units the gap is measured, and shrunk back to 0.00000001 along the same direction so that it stays
# tiny. Its average growth rate is lambda (Benettin et al. 1980)
lyapunov<-function(start,time=500,every=0.1,size=1e-8) {
  copies<-rbind(start,start+c(size,0,0))
  growth<-0
  rounds<-round(time/every)
  for(r in seq_len(rounds)) {
    for(k in seq_len(round(every/lorenz_dt)))
      copies<-rk4_step(copies,lorenz_dt,lorenz_rate)
    gap<-sqrt(sum((copies[2,]-copies[1,])^2))
    growth<-growth+log(gap/size)
    copies[2,]<-copies[1,]+(copies[2,]-copies[1,])*size/gap
  }
  result<-growth/(rounds*every)
  return(result)
}
lambda<-lyapunov(start)

Together for 20 time units, then apart. The second run starts 0.00000001 (a hundred-millionth) further along x than the first. On the chart below their x lies on one line until about t = 20.3, when the gap between them passes 1; then they go their own ways, and from t = 24.1 the gap is as large as the typical distance between two points of the butterfly, 18.6: the two runs have no more in common than two points taken at random.

Code
plot_ly(runs,x=~time) %>%
  add_trace(y=~first,type="scatter",mode="lines",name="First start",
            line=list(color=blue,width=2),hovertemplate="First start: %{y:.2f}<extra></extra>") %>%
  add_trace(y=~second,type="scatter",mode="lines",name="Start 0.00000001 further along x",
            line=list(color=orange,width=2),
            hovertemplate="Second start: %{y:.2f}<extra></extra>") %>%
  chart("x of two runs that start a hundred-millionth apart",lorenz_source,"x",
        "Time (time units of the Lorenz system)",
        x_axis=list(range=c(0,max(runs$time)),showgrid=FALSE),
        y_axis=list(zeroline=FALSE),
        shapes=list(list(type="line",x0=apart,x1=apart,y0=0,y1=1,yref="paper",
                         line=list(color=reference_gray,width=1.5,dash="dot"))),
        annotations=list(list(x=apart,y=1,yref="paper",text="they part",showarrow=FALSE,
                              xanchor="right",yanchor="top",xshift=-4,
                              font=list(size=12,color=dark_gray))),
        hovermode="x unified",legend=legend_top,margin=list(t=100,b=110),note_y=-0.28)
Code
rule<-data.frame(time=c(0,log(typical/nudge)/lambda))
rule$gap<-nudge*exp(lambda*rule$time)
plot_ly(runs,x=~time,y=~gap,type="scatter",mode="lines",line=list(color=blue,width=2),
        showlegend=FALSE,hovertemplate="Gap: %{y:.2e}<extra></extra>") %>%
  add_trace(data=rule,x=~time,y=~gap,type="scatter",mode="lines",hoverinfo="skip",
            line=list(color=reference_gray,width=1.5,dash="dash")) %>%
  chart("The gap between the two runs, on a log scale",lorenz_source,
        "Distance between the two states","Time (time units of the Lorenz system)",
        y_axis=list(type="log",exponentformat="power",dtick=2),
        x_axis=list(range=c(0,max(runs$time)),showgrid=FALSE),
        annotations=list(list(x=rule$time[2]/2,y=log10(nudge*exp(lambda*rule$time[2]/2)),
                              text=paste0("doubling every ",two(log(2)/lambda)," time units"),
                              showarrow=FALSE,xanchor="left",yanchor="top",xshift=8,
                              font=list(size=12,color=dark_gray))),
        margin=list(t=70,b=110),note_y=-0.28)

On a log scale, growth by doubling is a straight line, and the gap follows one, zigzagging as the runs go round their loops. The Lyapunov exponent of the Lorenz system, computed on this page over 500 time units, is λ = 0.90: a tiny gap doubles every 0.77 time units and grows ten-fold every 2.57. At that rate a gap of a hundred-millionth reaches 18.6 in 23.8 time units; the two runs took 24.1. After that the gap cannot grow any more, since nothing on the butterfly is further apart than its two ends, and it wanders.


3. What do 100 double pendulums do?

Code
gentle_spread<-spread(gentle)
wild_spread<-spread(wild)
first_time<-function(spread,size) {
  result<-pendulum_time[which(spread>size)[1]]
  return(result)
}
wild_cm<-first_time(wild_spread,0.01)
wild_10cm<-first_time(wild_spread,0.1)
wild_m<-first_time(wild_spread,1)
start_gap<-1000*wild_spread[1]

Together for about 5 seconds, then scattered. The lower arms of the 100 pendulums start within 0.099° of each other, so the weights at their ends start within 1.7 mm: on the movie they look like one pendulum. The wild pendulums, started with both arms at 120°, are 1 cm apart after 2.2 seconds, still too little to see; 10 cm apart after 5.3, when the movie shows them as a narrow wedge; and more than a meter apart after 7.0. Then they open like a fan, flip over the top one after another, and before the end of the movie they are everywhere their arms can reach. The gentle pendulums, started at 20°, are still one at the end.

Code
knitr::include_graphics(movie(gif_file()))

Movie of two sets of 100 double pendulums drawn in shades of blue, 18 seconds in real time. On the left, started with both arms at 20 degrees, the pendulums swing as one from start to end. On the right, started with both arms at 120 degrees, they swing as one for about 5 seconds, then open like a fan and scatter in every direction

The shade of each pendulum is the angle at which its lower arm started, from light blue (120° or 20°) to dark blue (0.099° more). While the fan opens, the shades still run in order from one edge to the other; once the pendulums scatter, the light and the dark are mixed. A real double pendulum does the same: Shinbrot and colleagues measured how fast small differences grow on one (Shinbrot et al. 1992).


4. Is a double pendulum always chaotic?

Code
# the growth rate while the gap is small: from 1 cm to 10 cm
pendulum_lambda<-log(10)/(wild_10cm-wild_cm)
energy_gentle<-pendulum_energy(gentle[1,,])[1]
energy_wild<-pendulum_energy(wild[1,,])[1]
# the largest change of the energy of any pendulum during the 30 seconds, as a share of its own
# energy at the start (a matrix of pendulum × time, divided by its first column)
energy_change<-function(run) {
  energy<-apply(run,1,pendulum_energy)
  result<-max(abs(energy/energy[,1]-1))
  return(result)
}
drift<-max(energy_change(gentle),energy_change(wild))
gentle_most<-1000*max(gentle_spread)

No: only when it swings hard enough. With both arms at 20°, the 100 pendulums stay together: in 30 seconds the weights at their ends are never more than 2.6 mm apart, against 1.7 mm at the start. Small swings are regular: the two arms rock in a mix of two steady rhythms, and a small difference grows slowly, at most in step with the time, never by doubling. Started at 120°, the pendulums have 25 times as much energy (44.1 joules more than hanging still, against 1.8), enough to swing over the top; then the gap between them doubles about every 0.91 seconds, until it fills the circle that their arms can reach.

Code
every<-seq(1,length(pendulum_time),by=5)
spreads<-data.frame(time=pendulum_time[every],gentle=1000*gentle_spread[every],
                    wild=1000*wild_spread[every])
# the name of each line at its right end: the gentle line at the top of its swings, the wild one
# where it ends
label_y<-c(gentle=log10(gentle_most),wild=log10(spreads$wild[nrow(spreads)]))
end_labels<-lapply(c("gentle","wild"),function(v)
  list(x=max(spreads$time),y=label_y[[v]],text=if(v=="gentle") "Gentle" else "Wild",
       showarrow=FALSE,xanchor="left",xshift=6,font=list(size=12,color=ink)))
plot_ly(spreads,x=~time) %>%
  add_trace(y=~gentle,type="scatter",mode="lines",name=paste0("Gentle: arms at ",gentle_angle,"°"),
            line=list(color=green,width=2),hovertemplate="Gentle: %{y:.1f} mm<extra></extra>") %>%
  add_trace(y=~wild,type="scatter",mode="lines",name=paste0("Wild: arms at ",wild_angle,"°"),
            line=list(color=orange,width=2),hovertemplate="Wild: %{y:.0f} mm<extra></extra>") %>%
  chart("How far apart the 100 pendulums are",pendulum_source,
        "Largest distance between two of them","Time (seconds)",
        y_axis=list(type="log",tickvals=c(1,10,100,1000),ticktext=c("1 mm","1 cm","10 cm","1 m"),
                    range=c(-0.2,3.6)),
        x_axis=list(showgrid=FALSE),annotations=end_labels,
        hovermode="x unified",legend=legend_top,margin=list(t=100,b=110,r=60),note_y=-0.28)

The computation can be checked: a pendulum without friction neither gains nor loses energy, and the energy of every pendulum stayed the same to within one part in 100,000,000 over the 30 seconds. So the steps are small enough, and the scattering comes from the pendulum, not from the arithmetic.


5. Why does a more precise start buy so little time?

Code
# 40 starts along the path of question 1, one every 2.5 time units. Each is rounded to 1, 2, ... 12
# decimals, as if copied from a printout, and moved on together with the exact start: when does
# each rounded run part from the exact one (the gap passes 1)? A matrix of start × decimals
digits<-1:12
parting_times<-function(exact,digits,time=60,size=1) {
  n<-nrow(exact)
  rounded<-do.call(rbind,lapply(digits,function(d) round(exact,d)))
  s<-rbind(exact,rounded)
  partner<-rep(seq_len(n),length(digits))
  parted<-rep(NA_real_,nrow(rounded))
  for(k in seq_len(round(time/lorenz_dt))) {
    s<-rk4_step(s,lorenz_dt,lorenz_rate)
    gap<-sqrt(rowSums((s[n+seq_len(nrow(rounded)),]-s[partner,])^2))
    parted[is.na(parted)&gap>size]<-k*lorenz_dt
  }
  stopifnot(!anyNA(parted))
  result<-matrix(parted,nrow=n)
  return(result)
}
exact<-as.matrix(path[match(seq(2.5,100,by=2.5),round(path$time,2)),c("x","y","z")])
times<-parting_times(exact,digits)
part<-colMeans(times)
part_low<-apply(times,2,quantile,0.1)
part_high<-apply(times,2,quantile,0.9)
fit<-lm(part~digits)
per_digit<-coef(fit)[["digits"]]

Each extra decimal buys the same short time: about 2.52 time units. On average over 40 starts along the butterfly, a run started from its state rounded to 3 decimals parts from the exact one at t = 7.5; rounded to 6 decimals, at t = 15.6; rounded to 12, a start a billion times more precise than with 3, at t = 30.0, only 4.0 times as long. Every decimal makes the first gap ten times smaller, and the system takes ln 10/λ = 2.57 time units, on average, to grow a gap ten-fold: so each decimal adds about that much time, and to see twice as far ahead the start has to be known to about twice as many decimals. From one start to another the time varies (the bars hold the middle 80% of the starts), because the butterfly stretches a gap faster in some places than in others.

Code
fitted<-data.frame(digits=range(digits),time=predict(fit,data.frame(digits=range(digits))))
averages<-data.frame(digits=digits,time=part,low=part-part_low,high=part_high-part)
plot_ly(averages,x=~digits,y=~time,type="scatter",mode="markers",
        marker=list(color=blue,size=9,line=list(color="#ffffff",width=2)),showlegend=FALSE,
        error_y=list(type="data",symmetric=FALSE,array=~high,arrayminus=~low,color=blue,
                     thickness=1.5,width=0),
        hovertemplate="%{x} decimals: they part at t = %{y:.1f} on average<extra></extra>") %>%
  add_trace(data=fitted,x=~digits,y=~time,type="scatter",mode="lines",hoverinfo="skip",
            line=list(color=reference_gray,width=1.5,dash="dash"),showlegend=FALSE,
            inherit=FALSE) %>%
  chart("When a rounded start parts from the exact one",lorenz_source,
        "Average time until they part (time units)","Decimals of the start",
        x_axis=list(dtick=1,showgrid=FALSE),y_axis=list(rangemode="tozero"),
        annotations=list(list(x=mean(digits),y=predict(fit,data.frame(digits=mean(digits))),
                              text=paste0("+",two(per_digit)," for every decimal"),
                              showarrow=FALSE,xanchor="left",yanchor="top",xshift=10,
                              font=list(size=12,color=dark_gray))),
        margin=list(t=70,b=110),note_y=-0.28)

Lorenz met this by accident in 1961, when he restarted a run of a small weather model from numbers that he had typed in from a printout. The printout showed fewer decimals than the computer kept, and the new run soon had nothing in common with the old one (Lorenz 1993). In his talk of 1972 he put the same rule in terms of the weather: small errors in the large weather patterns double in about three days, so every halving of the errors of observation would add three days to a good forecast; but small errors in the finer structure, such as the positions of single clouds, grow much faster and soon spread to the large patterns, so that “the hopes for predicting two weeks or more in advance are thus greatly diminished”. Half a century later the numbers agree: a good forecast of each day’s weather in the middle latitudes reaches about 10 days ahead, and a start ten times more precise would add up to 5 more (Zhang et al. 2019).


So, what does it mean?

Chaos is not chance: it is a rule that turns tiny differences into large ones, quickly.

  1. The Lorenz system draws a butterfly whose 134 loops in 100 time units switch wings 54 times, in no set order, and never repeat.
  2. Two runs a hundred-millionth apart stay together for 20 time units and are unrelated after 24: a tiny gap doubles every 0.77 time units.
  3. 100 double pendulums 0.001° apart swing as one for about 5 seconds and are scattered after 7.
  4. A gentle swing is not chaotic: at 20° the pendulums stay together; chaos needs enough energy for the arms to fold and flip.
  5. Precision buys little time: every extra decimal of the start adds the same 2.52 time units, which is why weather forecasts improve slowly, and why they may never reach far beyond two weeks.

What this does not show. The Lorenz system is a three-number cartoon of air heated from below, not a model of the atmosphere, and its time units are not days. Real weather has motions of every size, whose errors grow at different speeds: the small ones fastest, and they spill into the large ones (Lorenz 1969), which is why more precise observations alone cannot push the limit of forecasts back for ever. The pendulums are ideal: no friction, no air, stiff arms with all their weight at the ends. A real one slows down, and the times on this page hold for these starts only; other starts give other times, but the same picture. And no computer can follow one chaotic path exactly for long: its own rounding errors, in the 16th digit, grow like any other tiny difference. What a computation shows reliably is how fast differences grow and the shape of the motion, not where one pendulum will be after a minute.


Sources

Rendered with R 4.6.2 · plotly · ggplot2 · magick · ragg