Showing posts with label numpy. Show all posts
Showing posts with label numpy. Show all posts

Saturday, October 28, 2023

Numworks: Polynomial Fit with Numpy (Software version 21 or later)

Numworks:  Polynomial Fit with Numpy  (Software version 21 or later)



The scripts polyfit.py and polyfitg.py perfectly fit a polynomial to a set of points.  For a set of n points, a polynomial of degree n-1 can be perfect fit to the set of points.   For instance,  2 points fit a perfect line,  3 points fit a quadratic polynomial, and 4 points fit a cubic polynomial.    Software version 21 or later is required as the numpy module is used.  


Numworks:  polyfit


polyfit.py:    Fit a number of points to a curve using the numpy module

403 bytes


from math import *

import numpy as np


# 2023-09-25 EWS


n=input("number of points? ")

n=int(n)

d=n-1

x=np.ones(n)

y=np.ones(n)

k=0


while k<n:

  print("point "+str(k+1))

  x[k]=float(input("x? "))

  y[k]=float(input("y? "))

  k+=1


p=np.polyfit(x,y,d)

# list coefficients

print("polynomial vector:")

print("x**n:  coef")


for k in range(n):

  print(str(n-k-1),":  ",str(p[k]))


print(p)




Numworks:  polyfitg


polyfitg.py:   Same as polyfit except a graph of the polynomial is drawn.   The coefficients are shown for 3 before the graph is drawn.  

743 bytes 


from math import *

from time import *

from matplotlib.pyplot import *

import numpy as np


# 2023-09-25 EWS

n=input("number of points? ")

n=int(n)

d=n-1

x=np.ones(n)

y=np.ones(n)

k=0


while k<n:

  print("point "+str(k+1))

  x[k]=float(input("x? "))

  y[k]=float(input("y? "))

  k+=1


p=np.polyfit(x,y,d)


# list coefficients

print("polynomial vector:")

print("x**n:  coef")


for k in range(n):

  print(str(n-k-1),":  ",str(p[k]))


print("\nplotting...")

sleep(3)


# graphing portion

c=(np.max(x)-np.min(x))/100

xc=[]

yc=[]


for i in range(101):

  xp=np.min(x)+i*c

  yp=np.polyval(p,xp)

  xc.append(xp)

  yc.append(yp)


axis((min(xc)-.5,max(xc)+.5,min(yc)-.5,max(yc)+.5)) 

axis(True)

grid(True)

plot(xc,yc,color="purple")

show()





Eddie


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


Thursday, October 12, 2017

Adventures in Python: Plotting Sine and Cosine, The numpy Module

Adventures in Python:  Plotting Sine and Cosine, The numpy Module

This program will require that you have both numpy and matplotlib.  If you are working with Pythonista for the iOS, the two modules are included.  Other versions of Python require that you download matplotlib and numpy separately. 


Pointers:

1. The module numpy works with functions with lists as arguments.  There is a math function associated with numpy.  See the section on numpy functions below.

2.  It is helpful to set up all the graphing parameters before showing the graph with pylplot.show().

3. Color strings are six digit hexadecimal integers with the format ‘#RRGGBB’ (R = red, G = green, B = blue)

4.  To turn the plot grid on, use pyplot.legend().  To turn on the legend on use pyplot.legend().  Labels are defined in pyplot.plot. 


Program:

# this will require matplotlib
# download if needed

# radians mode is the default
import matplotlib
from matplotlib import pyplot

# will need numpy to generate lists
import numpy

# we will need math module for pi
import math

# generate lists
x = numpy.linspace(-2*math.pi, 2*math.pi, 50)
# sin and cos are included in numpy
y1 = numpy.sin(x)
y2 = numpy.cos(x)
y3 = numpy.sin(x)+numpy.cos(x)
# alt for y3: numpy.add(y1,y2)


# the plot begins
pyplot.plot(x,y1,color = '#228b22', label = 'sin x')
pyplot.plot(x,y2,color = '#ffa500', label = 'cos x')
pyplot.plot(x,y3,color = '#919811', label = 'sin x + cos x')


# turn grid on
pyplot.grid(True)
# labels
pyplot.title('Trig Plots 007')
pyplot.xlabel('x')
pyplot.ylabel('y')
# turn legend box on
pyplot.legend()
# show the plot
pyplot.show()

Output:




Some Numpy Functions

numpy.add(list 1, list 2)    Adds two lists, element by element.

numpy.subtract(list 1, list 2)   Subtracts list 2 from list 1, element by element.

numpy.mutiply(list 1, list 2)   Multiplies two lists, element by element.

numpy.divide(list 1, list 2)    Divides list 1 by list 2, element by element.

numpy.power(list 1, list 2)    Calculates list 1**list 2.

numpy.maximum(list 1, list 2)  Takes the maximum of each respective pair.

numpy.minimum(list 1, list 2)   Takes the minimum of each respective pair.

numpy.round(list, number of decimal places)  Round each element.

Other element by element operations: (one list arguments – Radians is the default angle measure)

numpy.square
numpy.sqrt
numpy.cbrt (cube root)
numpy.absolute
numpy.sin
numpy.cos
numpy.tan
numpy.radians (convert to radians)
numpy.asin
numpy.acos
numpy.atan
numpy.degrees (covert to degrees)
numpy.exp
numpy.log (ln)
numpy.real
numpy.imag
numpy.angle
numpy.log10 (log)
numpy.sinc
numpy.i0 (Bessel first kind, order 0)

Until next time,

Eddie


This blog is property of Edward Shore, 2017.

Saturday, September 30, 2017

Adventures in Python: Installing and Matplotlib Package

Adventures in Python: Installing and Matplotlib Package

October: Adventures in Python

I am going to spend some of October concentrating on programming in the popular program Python.  Python is available on most operating systems:  Windows, iOS (such as Pythonista), Android (most popular QPython), and Linux.  

Python comes in two versions, 2 and 3.  The latest version is 3.6.

My focus is on mathematics and mathematical application.  I plan to use a Windows version of Python and the iOS Python.

Python comes with several expansion modules out of the box:  math (mathematics), random (random numbers and generation), statistics, cmath (complex numbers), and time (time functions). 

However, if we want to generate plots, including histograms and box plots, we will need to download and add an appropriate package.  The package that I am going to use is matlibplot, which also contains the module numpy which allows for matrices and matrix calculations.  The file format of matlibplot is .whl (wheel). 

Download – Windows

Download Python here:  https://www.python.org/ 


I downloaded the Win32 verison.

When downloading, make sure you use custom installation. I recommend watching this YouTube video by APMonitor here:  https://www.youtube.com/watch?v=Ju6zw83PoKo&feature=youtu.be

The video saved me a lot of headaches when I tried to download and install Python, along with downloading and installing mathlibplot.  For instance, to install mathlibplot (which includes numpy), you will need to work with the Windows command prompt.

Note:  To install matplotlib, you must install pip and matplotlib thorugh the Windows Command Prompt, not the program itself.

For the Windows version, I am going to use the IDLE program which allows me to run Python both on the module and also create and run scripts. 




Android – installing matplotlib – Help Needed!

I tried to install matplotlib on QPython3 without success.  There documentation for this is scare and often not a help at all.   If anyone knows how to do it, please share.  I need type of version (Linux, win32, etc) is needed, what folder, etc. 

Download Pythonista – Apple iOS

For portable Python I am going to use the Pythonista app for Apple iOS engine.  It costs $9.99.  The best part about Pythonista is that numpy and matplotlib are both included.

More information about the app can be found here:  http://omz-software.com/pythonista/

Eddie

This blog is property of Edward Shore, 2017.



HP 67 Collection: October 2026

HP 67 Collection: Oct ober 2026 All examples are done in FIX 4. (DSP 4) Earth's Gravity at a Specific Latitude The true ea...