Saturday, January 30, 2021

TI-Nspire Python: Linear Regression

 TI-Nspire Python:  Linear Regression


Introduction


The following is a simple script to fit bivariate data using linear regression:


y = ax + b


a = slope

b = y-intercept


Download the document here:  https://drive.google.com/file/d/1trsa6oLdb0SG-1cHzog1stcbE6XY6BTv/view?usp=sharing


TI-Nspire Python Script:  linreg.py


# 2020-12-31 EWS

# linear regression 

from math import *


# enter and calculate data

xlist=[]

ylist=[]

n=int(input('n? '))

nb=0

sx=0

sx2=0

sy=0

sy2=0

sxy=0


for i in range(n):

  nb=nb+1

  print("Data Point "+str(nb))

  x=float(input('x? '))

  y=float(input('y? '))

  sx=sx+x

  sy=sy+y

  sx2=sx2+x**2

  sy2=sy2+y**2

  sxy=sxy+x*y

  xlist.append(x)

  ylist.append(y)


# slope

a=(sxy-sx*sy/nb)/(sx2-sx**2/nb)

# y-intercept

b=sy/nb-a*sx/nb

# correlation

r=(sxy-sx*sy/nb)/(sqrt(sx2-sx**2/nb)*sqrt(sy2-sy**2/nb))


# results

print("y = ax + b")

print("a= "+str(a))

print("b= "+str(b))

print("r= "+str(r))


The following script adds a plot of both the real and predicted data.


TI-Nspire Python Script:  linregplus.py


# 2020-12-31 EWS

# linear regression with plot

from math import *

import ti_plotlib as plt


# enter and calculate data

xlist=[]

ylist=[]

n=int(input('n? '))

nb=0

sx=0

sx2=0

sy=0

sy2=0

sxy=0


for i in range(n):

  nb=nb+1

  print("Data Point "+str(nb))

  x=float(input('x? '))

  y=float(input('y? '))

  sx=sx+x

  sy=sy+y

  sx2=sx2+x**2

  sy2=sy2+y**2

  sxy=sxy+x*y

  xlist.append(x)

  ylist.append(y)


# slope

a=(sxy-sx*sy/nb)/(sx2-sx**2/nb)

# y-intercept

b=sy/nb-a*sx/nb

# correlation

r=(sxy-sx*sy/nb)/(sqrt(sx2-sx**2/nb)*sqrt(sy2-sy**2/nb))


# results

print("y = ax + b")

print("a= "+str(a))

print("b= "+str(b))

print("r= "+str(r))


# predictive list

plist=[]

for i in range(n):

  p=a*xlist[i]+b

  plist.append(p)


# plot routine

# clear the screen

plt.cls()

# automatically fits the screen to fit the data

plt.auto_window(xlist,ylist)

# display the axes

# "on" plots axes and endpoints

# "axes" just plots the axes

plt.axes("on")


# select color - use RGB style

# denim blue, real data

plt.color(21,96,189)

plt.plot(xlist,ylist,".")

# orange, predictive data

plt.color(255,165,0)

plt.plot(xlist,plist,".")

# plot the graph

plt.show_plot()



Eddie


All original content copyright, © 2011-2021.  Edward Shore.   Unauthorized use and/or unauthorized distribution for commercial purposes without express and written permission from the author is strictly prohibited.  This blog entry may be distributed for noncommercial purposes, provided that full credit is given to the author. 


TI 30Xa Algorithm: Acceleration, Velocity, Speed

TI 30Xa Algorithm: Acceleration, Velocity, Speed Introduction and Algorithm Given the acceleration (α), initial velocity (v0), and...