Thursday, October 19, 2017

Adventures in Python: String Manipulation and Function/Derivative Table (Subroutines)

Adventures in Python:  String Manipulation and Function/Derivative Table (Subroutines)

String Manipulation

This script demonstrates several string functions:

length:  the number of characters in a string

stringname.replace(‘target string’,‘new string’):  replace a part of a string

stringname.capitalize(): capitalize the first letter of a string

stringname.split():  splits a string at its spaces

Other string functions:

stringname.lower(): makes all letters of a string to lower case

stringname.upper():  makes all letters of a string to upper case

You can join strings with the plus symbol ( + ).

The nice thing is that you won’t need to import any modules for the above string functions.

Script:

# program 008
print('Program 008: String Demo')
str1 = input('Please type some text.  ')
# input defaults to strings
# length
print('Length')
l = len(str1)
print('Length',l)
# capitalizes the first letter
print('Capitalize')
str2 = str1.capitalize()
print(str2)
# string splits at spaces
print('Split')
str3 = str1.split()
print(str3)
# replacement
str4 = str1
str4 = str4.replace('a','e')
str4 = str4.replace('u','a')
str4 = str4.replace('o','u')
str4 = str4.replace('i','o')
str4 = str4.replace('e','i')
print('Can you read this?')
print(str4)

Output:  with the “This is my demonstration.”

Program 008: String Demo
Please type some text.  This is my demonstration.
Length
Length 25
Capitalize
This is my demonstration.
Split
['This', 'is', 'my', 'demonstration.']
Can you read this?
Thos os my dimunstritoun.


Function/Derivative Table (Subroutines)

You can create user functions (subroutines) in python by the def structure.  You return results by the return command.

Script (you can enter whatever your function you like, I have imported the math module):

# Program 009 Using def and creating a table
# import math
import math

def fx(x):
     f = math.exp(-x**2/2)
     return f;
    
print('Function Table')
beg = float(input('start: '))
end = float(input('stop: '))
stp = float(input('step: '))

# loop begins
h = .00001
k = beg
print('k',':','f(x)',';','slope')
while k <= end:
     # function
     a = fx(k)
     # derivative
     b = fx(k+h)
     c = fx(k-h)
     d = (b - c)/(2 * h)
     print(k,',',a,',',d)
     print('- - - - - - - -')
     k = k + stp
           

Output (with start = 0, stop = 5, step = 1)

Function Table
start: 0
stop: 5
step: 1
k : f(x) ; slope
0.0 , 1.0 , 0.0
- - - - - - - -
1.0 , 0.6065306597126334 , -0.6065306596914066
- - - - - - - -
2.0 , 0.1353352832366127 , -0.27067056647955834
- - - - - - - -
3.0 , 0.011108996538242306 , -0.033326989618259056
- - - - - - - -
4.0 , 0.00033546262790251185 , -0.0013418505118650097
- - - - - - - -
5.0 , 3.726653172078671e-06 , -1.8633265866508763e-05
- - - - - - - -

Eddie


This blog is property of Edward Shore, 2017.

Tuesday, October 17, 2017

TI-84 Plus CE: Version 5.3 Highlights

TI-84 Plus CE:  Version 5.3 Highlights

Piecewise Function

The piecewise( function is added to the Math menu under the math submenu, option B.  As a result, the equation solver has been moved to option C.  The piecewise function can hold from 1 to 5 pieces.



Conditions Template

Version 5.3 adds 16 test templates involving the variable X to the Test menu ([2nd] [math]).  This is meant to compliment the new piecewise function, especially in function graphing.  However, the variable can be changed as needed.  The screen shot below shows a condition template with a piecewise function.



Demo:


Tangent Drawing Command Adds Option to Store Tangent line

When a function is drawn, you can calculate and draw the tangent line at any continuous point while you are on the graph screen.  Version 5.3 adds the option to store the Tangent line to any available graphing equation (Y# for example).  The new functionality is available only in the Function mode. 

To generate the Tangent line, press [2nd] [prgm] (draw), option 5 to call up the Tangent command.  Arrow to the desired point.  Press [graph/f5] (MENU) for options.  Select your options, then press [enter].   Use either arrow keys or enter a number to get to a point and commence drawing the tangent line.

A demonstration is shown below.



Program Editing Tools

It’s been a long time coming:  the TI-84 Plus CE now has editing tools!  We now can insert comments (comments are indicted with quotation marks), insert blank lines, copy, cut, and paste lines.  There is even an option to execute the program immediately.  It is all accessible from pressing [alpha] [graph/f5].


Running Archived Programs

You can now run archived programs without unarchiving the program into RAM first.  We still need to unarchive programs in order to edit them. 



Other

*  Running assembly programs will no longer require the asm( command.

* The fraction bar can be called by [alpha] [X,T,θ,n].

Documentation and Download

You can find additional details and other updates here and more tips here:  file:///C:/Users/Edward/Downloads/Whats-New-TI-84-Plus-CE-Graphing-Release-History%20(1).pdf

Download version 5.3 from Texas Instruments here:  https://education.ti.com/en/product-resources/whats-new-84-ce

Source:  Texas Instruments.  “TI-84 Plus CE Graphing Calculator Release History: v5.2 and above”  2017 (see above for the link)

Eddie


This blog is property of Edward Shore, 2017

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.

HP Prime and Casio fx-CG 50: Leap Year Test

HP Prime and Casio fx-CG 50: Leap Year Test

Introduction

The presented program tests whether a year is a leap year.  A leap year has 366 days instead of 365, with the extra day given to February (February 29).  The criteria for a leap year are:

* Leap years are year numbers evenly divisible by 4.  Example:  1992, 2016
* Exception:  years that are divisible by 100 but not divisible by 400.  Example:  2000 is a leap year, but 1900 and 2100 aren’t.

HP Prime Program ISLEAPYEAR

EXPORT ISLEAPYEAR(y)
BEGIN
IF FP(y/4) ≠ 0 OR (FP(y/100) == 0 AND FP(y/400) ≠ 0)
THEN
RETURN 0;
ELSE
RETURN 1;
END;
END;


Casio fx-CG 50 ISLEAPYR

“YEAR”? → Y
If Frac(Y ÷ 4) ≠ 0 Or (Frac(Y ÷ 100) = 0 And Frac(Y ÷ 400) ≠ 0)
Then
“No”
Else
“YES”
IfEnd

Eddie


This blog is property of Edward Shore, 2017.

HP 12C: Percent Markup and Percent Margin

HP 12C:  Percent Markup and Percent Margin

I would like to thank Gamo for this question. 

Calculating Percent Markup and Percent Margin

Two common calculations in business is calculating the percent margin and markup.  The formulas are:

Percent Markup = (Selling Price – Cost) / Cost

Percent Margin = (Selling Price – Cost) / Selling Prices

There is no dedicated keys on the HP 12C for this, but we can use either the percent change key ([ Δ% ]) key or the TVM keys.

Using the Percent Change Key

Percent Markup:  cost [ ENTER ] price [ Δ% ]

Percent Margin:  price [ ENTER ] cost [ Δ% ] [ CHS ] (note that the arguments are in reverse order)

Example:  Cost:  25.00,  Price:  36.00

Percent Markup:  25.00 [ENTER] 36.00 [ Δ% ],  result:  44.00

Percent Margin:  36.00 [ENTER] 25.00 [ Δ% ] [CHS], result:  30.56

Using the TVM Keys

Clear the registers before you begin.  For this exercise, PMT = 0.

Percent Markup with TMV solver (HP 12C):  
Let N = 1 and PMT = 0
[ i ] = percent markup
[ PV ] = cost (enter/displayed as a negative)
[ FV ] = price

For our example:
N = 1, PV = -25, FV = 36.  Solving for i gets 44.

Percent Margin with TMV solver (HP 12C):  
Let N = 1 and PMT = 0
[ i ] = percent margin (enter/displayed as a negative)
[ PV ] = price (enter/displayed as a negative)
[ FV ] = cost

For our example:
N = 1, PV = -36, FV = 25.  Solving for i, then pressing [CHS] obtains 30.56.

What is good about the above method is that you can solve for any of the variables.

More Methods:  Solutions Handbook

Detailed algorithms for business calculations can also be found in the HP 12C Advanced Solutions Handbook (see source below).  For the Platinum edition of the Solutions Handbook, refer to page 92. 

Source:
Tony Hutchins, Luiz Vieria, and Gene Wright.  HP 12C Platinum Solutions Handbook.  Hewlett Packard Development Company, L.P.  Rev. 03.04  2004

This book can be downloaded from this site (and others) at no cost:  https://support.hp.com/us-en/product/hp-12c-platinum-financial-calculator/384706/model/315565/manuals


Eddie


This blog is property of Edward Shore, 2017.

Sunday, October 8, 2017

Adventures in Python: Generating Random Numbers

Adventures in Python:  Generating Random Numbers

This program generates a list of random numbers between 0 and 1, using the pseudo-random number generator frac((π + t)^5). 

To use a pseudo-random number generator, you will need an initial seed.  This program uses the fractional part of the number of ticks from January 1, 1970.  To get ticks, you will need to import the time module.  Call the number of ticks by the time.time() function.

Python has no native fractional part.  To extract the fractional part of a number, the following formula is required, where t is any variable:

t = t – math.trunc(t)

The function math.trunc(t) truncates t and returns the integer part.

Keep in mind, to generate n items, use the for loop with the in range(0, n-1)

# Program 006 - Random Number Generation
print("Random number generation")

# import time, use as a seed
import time
t = time.time()
print

# since t is a floating number
# lets import math and use
# math.trunc

import math
t = t - math.trunc(t)

# We are going to use a psuedo-random
# formula to generate n numbers.  n
# will be an integer as range requires.
n = int(input("How many random numbers?"))
for k in range(0,n-1):
     t = (math.pi + t)**5
     t = t - math.trunc(t)
     print(t)

Output (15 numbers generated):

Random number generation
How many random numbers?15
0.8619577822222482
0.5526325838995945
0.045018018769951595
0.5829554424582284
0.7503835409480644
0.9988016770092827
0.770091723446285
0.8387765088751848
0.11795716208871454
0.9494124177641083
0.9088916269388392
0.2717401531838277
0.3329376152682926
0.38460892637095867
(your answers will vary)

Eddie


This blog is property of Edward Shore, 2017.

Adventures in Python: Combinations and Permutations

Adventures in Python: Combinations and Permutations

This program offers the user a choice of one of three calculations:

1.  Combinations, no repeats
2.  Permutations
3.  Combinations, with repeats

The program demonstrates how a menu is made.  Equality is tested with two equal signs (==).  A single equal sign (=) represents assignment for the Python.

The math.factorial function uses integers.

#  Program 005: Combinations, Permutations, Repeated Combination
#  Demonstration of the If structure

import math
# factorial is only for integers

# choices
# we will need to format the choice variable as an integer (number)
print("Make your choice:")
print("1.  Combination")
print("2.  Permutation")
print("3.  Repeated Combination")
choice = int(input("Choice: "))

# error condition, also input routine
if choice < 1 or choice > 3:
    print("Not a valid choice")
else:
    n = int(input("n = "))
    r = int(input("r = "))
    nf = math.factorial(n)
    rf = math.factorial(r)
    df = math.factorial(n-r)

# calculation test.  Equality is tested using 2 equal signs
if choice == 1:
    calc = nf/(df*rf)
    print("Combinations = ",calc)

if choice == 2:
    calc = nf/df
    print("Permutations = ",calc)

if choice == 3:
    calc = math.factorial(n+r-1)/(rf*math.factorial(n-1))
    print("Combinations = ",calc)

Example: n = 52, r = 5

Make your choice:
1.  Combination
2.  Permutation
3.  Repeated Combination
Choice: 1
n = 52
r = 5
Combinations =  2598960.0
>>>
Make your choice:
1.  Combination
2.  Permutation
3.  Repeated Combination
Choice: 2
n = 52
r = 5
Permutations =  311875200.0
>>>
Make your choice:
1.  Combination
2.  Permutation
3.  Repeated Combination
Choice: 3
n = 52
r = 5
Combinations =  3819816.0

Eddie


This blog is property of Edward Shore, 2017.

Adventures in Python: String Manipulation and Function/Derivative Table (Subroutines)

Adventures in Python:  String Manipulation and Function/Derivative Table (Subroutines) String Manipulation This script demonstrate...