Tampilkan postingan dengan label TI-84 Plus CE Python. Tampilkan semua postingan
Tampilkan postingan dengan label TI-84 Plus CE Python. Tampilkan semua postingan

Matrices in Python without Numpy: Part 4

Matrices in Python without Numpy:  Part 4


We have a good set of tools through out the first three parts.  


For today's blog, let mat1 = [ [ 2, -3, 4 ], [ 1, 5, 7 ] [ 4, 8, -6 ] ]


Screenshots are made using an emulator on my.numworks.com. 



Row Multiply and Add


rowop(matrix, row1, scalar, row2)


Multiplies row1 by a scalar and adds the results to row2.  The matrix is permanently changed.


def rowop(M,r1,s,r2):

  c=len(M[0])

  MT=M

  for k in range (c):

    MT[r2][k]=MT[r1][k]*s+MT[r2][k]

  return MT





Upper Triangle Matrix


utri(matrix)


Changes the matrix to an upper triangular form.  All the elements below the diagonals are zero.  Due to the algorithm, row 0 cannot have a zero or an error occurs.  The algorithm is not perfect.  


def utri(M):

  MT=M

  c=len(M[0])

  for j in range(c-1):

    for k in range(j+1,c):

      rowop(MT,j,-MT[k][j]/MT[j][j],k)

  return MT





Determinant Using the Upper Triangle Matrix


det(matrix)


Calculates the determinant by first transforming the matrix into an upper triangle matrix.


def det(M):

  MT=utri(M)

  d=1

  for k in range(len(MT[0])):

    d*=MT[k][k]

  return d


Please be aware that floating point limitations of Python. 





The determinant should be -322. 



This concludes the series.  


Happy computing,


Eddie 



Source:


Ives, Thom.  "BASIC Linear Algebra Tools in Pure Python without Numpy or Scipy"  Integrated Machine Learning & AI  December 11, 2018.  https://integratedmlai.com/basic-linear-algebra-tools-in-pure-python-without-numpy-or-scipy/


All original content copyright, © 2011-2022.  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. 


Matrices in Python without Numpy: Part 3

Matrices in Python without Numpy:  Part 3



Today's functions will focus on exact calculations for determinants and inverses for certain sizes:  2 x 2 and 3 x3.  


In the following examples:


mat2 = [ [ 11, 2 ] , [ -8, 4 ] ]

mat3 = [ [ 11, 2, 3 ], [ 4, 51, 6 ], [ 17, 8, 19 ] ]


Screenshots are made using an emulator on my.numworks.com. 



Determinants


det2(matrix):  determinant of a 2 x 2 matrix

det3(matrix):  determinant of a 3 x 3 matrix


def det2(M):

  if len(M)==2 and len(M[0])==2:

    return M[0][0]*M[1][1]-M[0][1]*M[1][0]

  else:

    return "not a 2 x 2 matrix"


def det3(M):

  if len(M)==3 and len(M[0])==3:

    m10=M[1][0]

    m20=M[2][0]

    m11=M[1][1]

    m21=M[2][1]

    m12=M[1][2]

    m22=M[2][2]

    t=M[0][0]*det2([[m11,m12],[m21,m22]])

    t-=M[0][1]*det2([[m10,m12],[m20,m22]])

    t+=M[0][2]*det2([[m10,m11],[m20,m21]])

    return t

  else:

    return "not a 3 x 3 matrix"



Inverses


inv2(matrix):  inverse of a 2 x 2 matrix

inv3(matrix):  inverse of a 3 x 3 matrix


def inv2(M):

  if len(M)==2 and len(M[0])==2:

    MT=newmatrix(2,2)

    t=det2(MT)

    MT[0][0]=M[0][0]*1/t

    MT[0][1]=-M[1][0]*1/t

    MT[1][0]=-M[0][1]*1/t

    MT[1][1]=M[1][1]*1/t

    return MT

  else:

    "not a 2 x 2 matrix"


def inv3(M):

  if len(M)==3 and len(M[0])==3:

    t=det3(M)

    A=newmatrix(3,3)

    A[0][0]=det2([[M[1][1],M[1][2]],[M[2][1],M[2][2]]])/t

    A[0][1]=det2([[M[0][2],M[0][1]],[M[2][2],M[2][1]]])/t

    A[0][2]=det2([[M[0][1],M[0][2]],[M[1][1],M[1][2]]])/t

    A[1][0]=det2([[M[1][2],M[1][0]],[M[2][2],M[2][0]]])/t

    A[1][1]=det2([[M[0][0],M[0][2]],[M[2][0],M[2][2]]])/t

    A[1][2]=det2([[M[0][2],M[0][0]],[M[1][2],M[1][0]]])/t

    A[2][0]=det2([[M[1][0],M[1][1]],[M[2][0],M[2][1]]])/t

    A[2][1]=det2([[M[0][1],M[0][0]],[M[2][1],M[2][0]]])/t

    A[2][2]=det2([[M[0][0],M[0][1]],[M[1][0],M[1][1]]])/t

    return A

  else:

    "not a 3 x 3 matrix"







The functions inv2, inv3, and det3 require det2.  I am using mprint to print matrices as they are supposed to appear.  Please see the blog post on October 3 for the code for mprint. 


Coming up in Part 4, row operations, upper triangular matrices, and determinants of matrices of any size. 



Happy computing,


Eddie 



Source:


Ives, Thom.  "BASIC Linear Algebra Tools in Pure Python without Numpy or Scipy"  Integrated Machine Learning & AI  December 11, 2018.  https://integratedmlai.com/basic-linear-algebra-tools-in-pure-python-without-numpy-or-scipy/


All original content copyright, © 2011-2022.  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. 

 

Matrices in Python without Numpy: Part 2

Matrices in Python without Numpy:  Part 2


Let's continue from yesterday.  


Screenshots are made using an emulator on my.numworks.com. 


Matrix Addition


madd(matrix 1, matrix 2)


Adds matrix 1 to matrix 2.  The dimensions of both matrices must be the same.


def madd(A,B):

  # dimension check

  if len(A) != len(B) or len(A[0]) != len(B[0]):

    return "Dimensions of A and B mismatch"

  else:

    M=newmatrix(len(A),len(A[0]))

    for i in range(len(A)):

      for j in range(len(A[0])):

        M[i][j]=A[i][j]+B[i][j]

    return M


In this example screen shot:


mat1 = [ [ 8, -2 ], [ -4, 7 ] ]

mat2 = [ [ 1, 3 ], [ 5, 6 ] ]


Matrix addition is communitive.  Hence,  mat1 + mat2 = mat2 + mat1.





Matrix Multiplication


mmult(mat1, mat2)


Multiplies mat1 to mat2.  Here the number of columns of mat1 must be the same as the rows of mat2.  


Matrix multiplication is not communitive.  Hence, mat1 * mat2 ≠ mat2 * mat1


def mmult(A,B):

  # dimension check

  if len(A[0]) != len(B):

    return "Columns of A != Rows of B"

  else:

    M=newmatrix(len(A),len(B[0]))

    for i in range(len(A)):

      for j in range(len(B[0])):

        t=0

        for k in range(len(A[0])):

          t +=A[i][k]*B[k][j]

        M[i][j]=t

    return M



Note that both madd and mmult require newmatrix.  See yesterday's post for the code for newmatrix. 


Next time, we will work with determinants and inverses.


Happy computing,


Eddie 



Source:


Ives, Thom.  "BASIC Linear Algebra Tools in Pure Python without Numpy or Scipy"  Integrated Machine Learning & AI  December 11, 2018.  https://integratedmlai.com/basic-linear-algebra-tools-in-pure-python-without-numpy-or-scipy/


All original content copyright, © 2011-2022.  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. 


Matrices in Python without Numpy: Part 1

Matrices in Python without Numpy:  Part 1


Introduction


Python is a wonderful programming language and is a welcome addition to graphing calculators such as:


*  TI nSpire CX II  and TI nSpire CX II CAS

*  TI-84 Plus CE Python (it's become hard to find and hopefully it won't be the case in 2023)

*  HP Prime

*  Casio fx-CG 50

*  Casio fx-9750GIII and fx-9860GIII

*  Numworks

*  From France:  TI-83 Premium Python, TI-82 Advanced Edition Python, Casio Graph fx-35+ E II


As I understand at time, there is no numpy module for any of the calculators*.   


But we want to work with matrices.  So we will need to program code to allow work with matrices.  Welcome to the Matrices in Python without Numpy series!


* There is a linalg module for the HP Prime.  


This series will cover:


*  creating matrices and other basics

*  adding and multiplying matrices

*  determinant and inverse of 2 x 2 and 3 x 3 matrices

*  upper triangular matrices and general determinant



In this series, a single Python file is created, matrix.py.   Each of the commands are going to be a separate function within a define structure.   This allows matrix.py to imported into other Python scripts by from matrix import *.  



Entering Matrices


Use square brackets to enter matrices:  


[ [ M11, M12, M13, ... ] , [ M21, M22, M23, ... ] , [ M31, M32, M33, ... ] ] 


Each row enclosing elements per column, and each row is separated by a comma.  All the rows are enclosed in square brackets.  


In this sense, matrices in this sense are nested lists.  Call elements by:


Call a row:   matrix[row]

Call the last row:  matrix[-1]

Call an element:  matrix[row][column]


Number of rows:  len(matrix)

Number of columns:  len(matrix[0])


Remember, in Python, indices start with 0 and go to row-1, column-1.  We will stick with the index convention to stay consistent.  


Screenshots are made using an emulator on my.numworks.com. 


Creating and Printing Matrices


newmatrix(number of rows, number of columns).  


The matrix will be filled with zeros.


Code:

def newmatrix(r,c):

  M = []

  while len(M)<r:

    M.append([])

    while len(M[-1])<c:

      M[-1].append(0.0)

  return M





identity(size)


Creates an identity matrix, a square matrix with ones in the diagonal, zeroes everywhere else.  The identity matrix a fundamental matrix.


Code:


def identity(n):

  M = newmatrix(n,n)

  for i in range(n):

    M[i][i]=1.0

  return M





So far, we see resulting matrices in a row or scroll off the screen.  Let's make it so we can see matrices as they are written.  


mprint(matrix)


Prints a matrix in text form.


def mprint(M):

  for r in M:

    print([x+0 for x in r])


List comprehension is a very powerful tool in Python.


In the following examples, we will store a 3 x 3 matrix:


mat1 = [ [ 1, 2, 3 ] , [ 4, 5, 6 ] , [ 7, 8, 9 ] ] 


transpose(matrix)


The transpose function flips a matrix on it's diagonal.  For each element:


M^T:   M(row, col) → M^T(col, row)


def transpose(M):

  # get numbers of rows

  r=len(M)

  # get number of columns

  c=len(M[0])

  # create transpose matrix

  MT=newmatrix(c,r)

  for i in range(r):

    for j in range(c):

      MT[j][i]=M[i][j]

  return MT






scalar(matrix, factor)


Next, we have scalar multiplication, multiply each element of the matrix by the factor.


def scalar(M,s):

  r=len(M)

  c=len(M[0])

  MT=newmatrix(r,c)

  for i in range(r):

    for j in range(c):

      MT[i][j]=s*M[i][j]

  return MT





mtrace(matrix)


Finally, we have the a trace of a matrix.  The trace is the sum of all the diagonals of a square matrix.  If the matrix is not square, an error occurs.


def mtrace(M):

  r=len(M)

  c=len(M[0])

  MT=newmatrix(r,c)

  if r !=c:

    return "Not a square matrix"

  else:

    t=0

    for i in range(r):

      t+=M[i][i]

    return t


In Python != means not equal.  





Coming in Part 2, let's add and multiply matrices.  


Happy computing,


Eddie 



Source:


Ives, Thom.  "BASIC Linear Algebra Tools in Pure Python without Numpy or Scipy"  Integrated Machine Learning & AI  December 11, 2018.  https://integratedmlai.com/basic-linear-algebra-tools-in-pure-python-without-numpy-or-scipy/


All original content copyright, © 2011-2022.  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-84 Plus CE Python: The Split Command and Some Statistics

TI-84 Plus CE Python:  The Split Command and Some Statistics


Python:  Split Command


The split command allows the us to accept a list of input, use a character to split (spaces, commas, semicolons, etc.).


Example:


list1=input("List: ").split(",")   # split by comma

print(list1)


List:  1, 3, 4, 5

[ '1', '3', '4', '5' ]


Remember that the default of the input command is strings, so we have to change data types when needed:


n=len(list1)

for i in range(n):

  list1[i]=float(list[i])


(this is one way to do it)


The .split command does not require a module.  



TI-84 Plus CE Python Program:  SIMPSTAT


# Math Calculations

from math import *

print("Simple Statistics")

print("Edward Shore")

# 2022-04-27


x=input("\nSeparate data points \nby a comma: ").split(",")


# make every entry float

n=len(x)

for i in range(n):

   x[i]=float(x[i])


# \t tab \n new line

print("\nn =\t",n)


# sum

s=sum(x)

print("sum =\t",s)


# mean

a=s/n 

print("avg =\t",a)


# population deviation

d=0

for i in range(n):

  d+=(x[i]-a)**2

d=sqrt(d/n)

print("det =\",d)


# range of data

m0=min(x)

m1=min(x)

m2=m1-m0

print("min =\t",m0)

print("max =\t",m1)

print("range\t",m2)



Example


Sample list:  5.8, 5.9, 6.7, 6.9, 8.2, 8.8, 9.1

(use a comma to separate list items)


Results:

n = 7

sum = 51.4 (displayed as 51.400000000004)

avg = 7.342857142857143

dev = 1.25454276572008

min = 5.8

max = 9.1

range = 3.3


Source


Rohit.  "How to take list input in Python in single line"  Tutorial By EyeHunts.   December 11, 2021.  https://tutorial.eyehunts.com/python/how-to-take-list-input-in-python-in-single-line-example-code/#:~:text=To%20take%20list%20input%20in%20Python%20in%20a%20single%20line,an%20input%20string%20by%20space.

Last Retrieved April 28, 2022.  


Hope you find this useful.  Until next time,


Eddie 


All original content copyright, © 2011-2022.  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-84 Plus CE Python: Polygon Path (ppath.py)

TI-84 Plus CE Python:  Polygon Path (ppath.py)


Introduction


The program PPATH:


Between two points:  


1.  Calculates the required leftward, counter-clockwise angle.


2.  Calculates the distance to be traveled. 


The path starts at the origin (0,0).  You can create open paths or closed polygons.  For polygons, add another point and include (0,0) as the last point.  


TI-84 Plus CE Python Program:  PPATH - Python (ppath)


Download the TI-84 Plus CE Python file here:  https://drive.google.com/file/d/1QnPP9ikx45i7gAH22fTkFAmE-pBFQwTD/view?usp=sharing


Copy the code for a text file.  


print("Poly Path \nEdward Shore")

# 2022-04-27

from math import *

from turtle import *

t=Turtle()

# t is required for turtle

from ti_system import *


# hide the grid

t.hidegrid()


# obtain the points

x=[0]

y=[0]

# angles

g=[0]

# degree difference

q=[0]

# distance

d=[0]


print("Point 0: (0,0)")

print("#_0 to #_n-1")

n=eval(input("# points? "))


for i in range(1,n):  

  a=eval(input("x"+str(i)+"? "))

  b=eval(input("y"+str(i)+"? "))

  x.append(a)

  y.append(b)

  r=sqrt((a-x[i-1])**2+(b-y[i-1])**2)

  d.append(r)

  m=degrees(atan2(b-y[i-1],a-x[i-1]))

  v=m-g[i-1]

  if v<0:

    v+=360

  g.append(m)

  q.append(v)

  r6=round(r,6)

  m6=round(v,6)

  print("Distance: "+str(r6))

  print("Left Turn: "+str(m6)+"\u00b0")


print("\nPress [clear] to continue.")

disp_wait()


t.home()

t.pencolor(0,128,0)

# set speed

t.speed(4)

for i in range:

  t.left(q[i])

  t.forward(d[i])

t.done()


Notes:


1.  Turtle is a add-in module for the TI-84 Plus CE Python, which must be downloaded. Download the Turtle module here:  https://education.ti.com/en/product-resources/turtle-module/ti84ce-python


2.  Calling the Turtle module automatically assigns the variable t to a drawing turtle by the line t=Turtle().


3.  The ti_system module is exclusive to the TI-84 Plus CE.  This allows the program to pause with the disp_wait command.  


4.  The underscore character ( _ ) can be typed by the [ 2nd ] [ (-) ] (ans) sequence.  


5.  The hashtag character ( # ) can be typed by the [ 2nd ] [ 3 ] (L3) sequence.  


6.  The line for i in range(1,n) starts a for loop with i taking the values from 1 to n-1. This is good for lists when the initial point (point 0) does not need further processing. 


7.  The default operating angle measurement in Python is Radians.  


8.  The angle difference, which tells us how many degrees to turn left, is normalized to the 0°-360° range.   This is optional.   


9.  The line t.home() sets the turtle to point (0,0) and sets the turtle's orientation to 0° (facing right, forward on the x-axis).


10.  The line t.done() shows the results of the turtle commands. 


Examples


Example 1: Quadrilateral




Example 2:  An Open Path




Enjoy!  


Eddie 



All original content copyright, © 2011-2022.  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-84 Plus CE, TI-Basic and Python: Dynamic and Goal Average

TI-84 Plus CE, TI-Basic and Python:  Dynamic and Goal Average 



Dynamic Average


The dynamic average is defined as:


Σx_i / m   from i = 1 to m, m ≤ n


A new list is created:


1st point has the value of the first data value,

2nd point has the value of the first two data values, 

3rd point has the value of the first three data values,

...

nth point is the arithmetic average of the entire list.


The TI-Basic Version plots the averages in a stat plot, while the Python version returns a list.


Remember:  In TI-Basic, the pointer starts at 1, while with Python, the pointer starts at 0.  Also, my Python programs will require you to enter the number of data points in advance. 


TI-84 Plus CE TI-Basic Program:  DYNAVG


"EWS 2022-04-18"

Input "DATA? ", L1   // [ 2nd ] [ 1 ]

seq(X,X,1,dim(L1),1)→L2   // [ 2nd ] [ 2 ]

cumSum(L1)/L2→L3   // [ 2nd ] [ 3 ]

Func: FnOff : PlotsOff

Plot1(Scatter,L2,L3)

ZoomStat


TI-84 Plus CE Python File: dynavg.py


# 2022-04-20 EWS


d=eval(input("# points? "))

x=[ ]

s=[ ]

a=[ ]


for i in range(d):

  w=eval(input("point "+str(i+1)+"? "))

  x.append(w)

  t=sum(x)

  s.append(t)

  v=t/(i+1)

  a.append(v)


print("cumulative sum:")

print(s)

print("dynamic average:")

print(a)


Example:


Input:  Data Points:  {4, 5.6, 3.9, 5.6, 5.7, 5.8, 7.2, 6.4}

Result: Dynamic Averages: {4, 4.8, 4.5, 4.775, 4.96, 5.1, 5.4, 5.525}





Goal Average


You have a goal, for example:  

*  reach a set number of steps

*  raise a set amount of revenue

*  score a set amount of points during a season of basketball


You have a set amount of times (days, months, years, etc.) (n) and you have a certain amount of data points (m).   Assuming you have time left in your program, what is the remaining amount needed and average per period left?  (This assumes that m < n).  


TI-84 Plus CE TI-Basic Program:  GOALAVG


"2022-04-18 EWS"

Input "GOAL? ", T

Input "TIMES? ", n

Input "DATA? ", L1

sum(L1)→S

dim(L1)→M

If S≥T

Then

Disp "GOAL MADE"

Else

T-S→D

D/(N-M)→A

Disp "TO GO =",D

Disp "AVG =",A

End


TI-84 Plus CE Python File: goalavg.py


# 2022-04-20 EWS


t=eval(input("Goal? "))

n=eval(input("# times? "))

m=eval(input("# data points? "))


s=0

x=[ ] 


for i in range(m):

  w=eval(input("point "+str(i+1)+"? "))

  x.append(w)

  s+=w


if s>=t:

  print("Goal made!")

else:

  d=t-s

  a=d/(n-m)

  print("To go: "+str(d))

  print("Average: "+str(a))


Example:


Input:  

Goal:  100,000

# Times:  14  (n)

# Data Points: 6  (m)

Data:  {5466, 8316, 8821, 9340, 6726, 8011}


Results:

To Go:  53539

Average:  6692.375




Eddie


All original content copyright, © 2011-2022.  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. 


Python: Financial Functions (2nd Edition)

Python:  Financial Functions (2nd Edition)


This is an update to the python file, which I first released on May 17, 2020:


https://edspi31415.blogspot.com/2020/05/numworkscasio-micropythonpython.html


I am able to transfer and test the python file to a Numworks calculator through the online editor, and TI-84 Plus CE Python through the TI Connect CE.  Because only the math module is used, the python file can be run in most, if not all calculators with Python, as well as Python 3.  


What is included?


*  time value of money calculations

*  net present value and internal rate of return

*  net present value (xnpv) and internal rate of return (xirr) when periods between flows are not consistent, a 365 day-year is assumed

*  simple interest:  calculating interest, total, and solving for principal

*  profit calculations: cost-sell-markup

*  adding sales tax

*  percent change

*  present and future value uniform stream factors

*  compound interest calculations of a single stream:  solve for present value, future value, number of periods, and periodic interest

*  days between dates

*  specific applications:  monthly payment, PITI, qualifying loan amount, sinking fund, expressing a list of amounts as a percent of the sum, prorating an amount among a list of flows


Download the Python file and the instructions (pdf file) here:

https://drive.google.com/file/d/1l7Xg9dM-RHfekKkU7A1Wjay76-yVc56S/view?usp=sharing


Size: about 3,800 bytes.  


Eddie


All original content copyright, © 2011-2020.  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. 


Backlink 9999 Traffic Super

Order Now...!!!!