Linear Relations

Given a relation between x and y, determine if the relation is linear. Relation:
          x = [5, 1, -10, -5, -4, -9, -6, -3, -1, 9]
          y = [5, -3, -25, -15, -13, -23, -17, -11, -7, 13]
        
Fig 1. Plot showing the relationship between x and y.
Notes and Code Outcome

Plotting points

You could go in by hand and draw each point as a sphere, however, it is easier if we use a loop.

              x = [5, 1, -10, -5, -4, -9, -6, -3, -1, 9]
              y = [5, -3, -25, -15, -13, -23, -17, -11, -7, 13]

              for i in range(len(x)):
                  sphere(pos = vec( x[i], y[i], 0 ), radius = 0.5)
            
one Lines 1 and 2 we make two lists of the x and y values. Any value in a list can be referenced using the index for its location. The first value in the x list would be referenced by x[0] (the value is 5). The second item in the x list would be x[1] (which is equal to 1).

on Line 4, we make a for loop that checks the length of the list x and loops that many times. Each time it loops, it makes the variable i equal to the index of the loop (so i goes from 0 to 9 in this case, since the x list has 10 items in it).

on Line 5, we set the position of the spheres to the x and y values that go with the index i. So, the first time through the loop, line 5 is interpreted as:


                  sphere(pos = vec( x[0], y[0], 0 ), radius = 0.5)
            
which gives the first values in the x and y lists, making the vector equivalent to vec( 5, 5, 0).

The second time through the loop i becomes 1 so:


                    sphere(pos = vec( x[1], y[1], 0 ), radius = 0.5)
              
and the vector becomes vec( 1, -3, 0 )

Programatic Linear Relations

There are a number of ways to do this, but we'll try this one:
  1. Take the first two coordinates and determine the equation of the straight line between them.
  2. Compare the rest of the points to the first point and see if the equations are the same.
1) The equation of a straight line is perfectly described by its slope (m) and intercept (b). So, take the first two points and determine m and b.
Show Notes ▼
Now we need to make a loop that starts from the third point and goes to the end of the x list.
Show Notes ▼
As you can see, this prints out the values 2 through 9. When given two values, the range function interprets the first as the starting value and the second as the stop.

Comparing slope and intercept values.

Now assume that each time through the loop we calculate the slope and intercept and call them new_m and new_b. We can check to see if the new values are the same as the original values. If they're not, we print that the relationship is not linear and break out of the loop.
Show Notes ▼

Peek at the code for the new_m and new_b:

Show Notes ▼

Testing

Click the link below to get a new dataset. There will be a 50-50 chance that it is a linear relation.
Generate Dataset


            
Answer: if linear:
Show Notes ▼