Wednesday, October 25, 2017

Adventures in Python: User-Entry Function

Adventures in Python:  User-Entry Function

The following script allows the user to enter a function, including math functions (math.sqrt, math.sin, etc).  The function is entered as string and when calculation is needed, the eval function is called. 

Script:

# Program 010:  Asking for a function - Using Eval
# To generate a table

# allow for math functions
import math


# ask for the parameters
print('Generate f(x): You can use math. functions')
print('Such as math.sqrt, math.sin, math.exp, etc.')
print('Remember the default angle measure is radians.')
print('Use math.pi for \u03C0')
# f(x) and parameters will be entered as a string
fx = input('Please enter f(x): ')
# use float for end marks
beg = input('Beginning point:  ')
end = input('Ending point:  ')
step = input('Step: ')
# use eval to evaluate the parameters, turning them into floating numbers
beg = eval(beg)
end = eval(end)
step = eval(step)


print('BEGIN')

# since a floating number with begin, end, and step may be used,
# we must use a while loop instead of a for loop
k = beg
while k<=end:
    # function evaluation
    x = k
    y = eval(fx)
    #  print the data to six decimal places
    x = round(x,6)
    y = round(y,6)
    print(x,',',y)
    print('-----')
    # use += for storage arithmetic
    k += step

# end of table
print('END')

Example:

f(x) = √(x^2 + 1) from x = 0 to x = 4, step 0.5

Result:

Generate f(x): You can use math. functions
Such as math.sqrt, math.sin, math.exp, etc.
Remember the default angle measure is radians.
Use math.pi for π
Please enter f(x): math.sqrt(x**2+1)
Beginning point:  0
Ending point:  4
Step: 0.5
BEGIN
0 , 1.0
-----
0.5 , 1.118034
-----
1.0 , 1.414214
-----
1.5 , 1.802776
-----
2.0 , 2.236068
-----
2.5 , 2.692582
-----
3.0 , 3.162278
-----
3.5 , 3.640055
-----
4.0 , 4.123106
-----
END

Pretty straight forward.  I hope you are enjoying this series on Python.  Until next time,

Eddie


This blog is property of Edward Shore, 2017

Sunday, October 22, 2017

Retro Review: HP 95LX

Retro Review:  HP 95LX




Essentials

Company:  Hewlett Packard
Years:  1991 - 2003
Type:  Palmtop PC (a very early version of the laptop)
Applications:  HP Calc, Lotus 1-2-3, Memo, Phone, DOS Prompt
Memory:  512,000 byte ROM, 1 MB RAM
Operating System: Microsoft MS-DOS 3.22
Original Price:  around $550 to $699
Today’s Price: can be very reasonable, anywhere from $40 to upwards of $200

Batteries:  2 AA batteries to run it, 1 CR2032 backup battery, can be powered by AC connector

This review will mainly focus on the HP Solve and Lotus 1-2-3 apps, as if I had not have the chance to try other apps at the time of this review.

Special Thanks

Thank you to Dave Bitten for this wonderful computer! This is the first portable computer of the 1990s HP series that I have.  I traded my Casio fx-Algebra 2.0.

Features

The HP 95LX has a rich variety of applications, including:

*  Appointment Book
*  Phone Book
*  Memo
*  Lotus 1-2-3
*  HP Calc (what the HP 19C would look like if it became a graphing calculator)

The HP 95LX can also hold a RAM disk, for permanent storage. 

HP Calc

The HP Calc is based off the HP 19B calculator, but adds a graphing calculator component.  The HP Calc can be operated for in either Algebraic or RPN (reverse polish notation).  HP Calc had financial solvers (time value of money, interest conversion, cost/sell/margin/markup), conversions (currency, length, area, volume, mass), and scientific functions (random numbers, logarithms, exponentials, trigonometry), and list editor.   

The solver is also based off the HP 19B, and also includes all the advanced features of the type of solver that was present on the HP 17BII+, HP 17B, and HP 27S.

* IF:  If statement with one command then and else command.  If statements can be nested.
* SIGMA:  The sum of a sequence.  The increment is specified.  Similar to Σ(f(x), x=a, b).
* S:  Solve:  Used in an IF statement, dictates which calculations to make depending of which variable is solved.
*  L:  Let: stores a value in a variable during a formula.
* G:  Get: recalls a variable during a formula

Example:  0*L(var:f(var)) + h(G(var) and other constants)

Lotus 1-2-3

Before Microsoft Excel, Lotus 1-2-3 was the favorite of spreadsheet applications.  Lotus 1-2-3 is easy to use with a good resource, like the awesome HP 95LX manual, download here:  http://hpmuseum.net/exhibit.php?hwdoc=202

What is really nice about the Lotus 1-2-3 is the ease of creating macros.  The only caveat is the macro is typed in code (depending on key stroke, such as \ for Menu, the first letter to choose commands, a tilde (~) for an enter, and other commands to move the cursor or ask for input).  Macros are assigned to the keyboard (called by Alt + letter). 

On Lotus 1-2-3, date functions handle years between 1900 and 2099.

Keyboard

The ON key toggles the HP 95LX on and off.  No waiting for the computer to start up, which is nice.  The keyboard is a QWERT keyboard.  Even though the keys are little small, they are pleasure to press and keys are responsive. 

Display

I am also impressed with HP 95LX’s sharp display.  The text on screen is very readable. The screen is not backlit, understandable for the technology of the early 1990s, which backlighting would put a high demand on its battery. 

Verdict… so far

I am very happy to have an HP 95LX.  If (really when) I get a chance, I want to take a look at DOS programming, playing around and expanding the limits of both HP Calc’s solver and Lotus 1-2-3.  So far, so good. 

Source:

Hewlett Packard.  “History of the HP 95LX computer” http://www.hp.com/hpinfo/abouthp/histnfacts/museum/personalsystems/0025/0025history.html  Retrieved October 17, 2017. 

Eddie


This blog is property of Edward Shore, 2017

HP Prime and Casio fx-CG 50: 3 x 3 Magic Squares

HP Prime and Casio fx-CG 50: 3 x 3 Magic Squares

Background

A magic square is a square of integers where each row, column, and diagonal have the same sum.  For example:

2
9
4
7
5
3
6
1
8

Each row, column, and diagonal of this magic square has a sum of 15. 

A proper magic square has the integers 1 through n^2, n is the size of the magic square.  A non-normal magic square follows the sum rule, but different integers than the 1 to n^2 sequence is allowed.

The program MAGICSQ3 generates random 3 x 3 non-normal magic squares.  The sum of each row, column, and diagonal are given. 

HP Prime Program: MAGICSQ3

EXPORT MAGICSQ3()
BEGIN

// Random Magic Square 3 X 3
// 2017-10-06 EWS
LOCAL x,k,r,mat,s,t,l;

// Initialization
r:=RANDINT(−5,200);
k:=RANDINT(1,3);
l:=MAKELIST(k*X,X,r-4*k,
r+4*k,k);
l:=SORT(l);
s:=ΣLIST(l);
t:=s/3;
mat:=MAKEMAT(0,3,3);

// Generation
mat(2,2):=l(5);
mat(1,1):=l(1);
mat(3,3):=l(9);
mat(1,3):=l(2);
mat(3,1):=l(8);
mat(1,2):=t-mat(1,1)-mat(1,3);
mat(2,1):=t-mat(1,1)-mat(3,1);
mat(2,3):=t-mat(1,3)-mat(3,3);
mat(3,2):=t-mat(3,1)-mat(3,3);

// Tranpose?
IF RANDINT(0,1) THEN
mat:=TRN(mat);
END;

// Results
RETURN {mat,t};

END;

Casio fx-CG50G Program:  MAGICSQ3

"2017-10-06 EWS"
RanInt#(-5,200)->R
RanInt#(1,3)->K
Identity 3->Mat A
Seq(K*X,X,R-4*K,R+4*K,K)->List 1
Sum List 1->S
S/3->T
List 1[5]->Mat A[2,2]
List 1[1]->Mat A[1,1]
List 1[9]->Mat A[3,3]
List 1[2]->Mat A[1,3]
List 1[8]->Mat A[3,1]
T-Mat A[1,1]-Mat A[1,3]->Mat A[1,2]
T-Mat A[1,1]-Mat A[3,1]->Mat A[2,1]
T-Mat A[1,3]-Mat A[3,3]->Mat A[2,3]
T-Mat A[3,1]-Mat A[3,3]->Mat A[3,2]
If RanInt#(0,1)=1
Then
Trn Mat A->Mat A
IfEnd
"TARGET SUM:"
T
Mat A

Note:  = Disps

Your results will vary.  Happy Halloween (one week to go!)

Sources:

Learn-With-Games.Com  “Magic Square Solution”  http://www.learn-with-math-games.com/magic-square-solution.html  Retrieved October 6, 2017
William H. Richardson.  “Non-Normal Magic Squares.”  http://www.math.wichita.edu/~richardson/mathematics/magic%20squares/notnormalmagicsquare.html  Retrieved October 22, 2017

Eddie


This blog is property of Edward Shore, 2017.

HP Prime: BREAK vs. CONTINUE

HP Prime:  BREAK vs. CONTINUE

Introduction

Ever needed to end a loop early?  Find yourself executing a loop where the counter becomes a value that causes an execution error?  An example where this might happen is a loop where a function is divided by the counter variable, and during the loop the counter variable takes the value of 0. 

The HP Prime offers two ways to mitigate potential problems in loops:

1.  You can terminate the loop at that point by using BREAK.

2.  You can skip that loop’s iteration by using CONTINUE.

You can specify how many loop structures are affected by using either the BREAK n or CONTINUE n format. 

A Simple Example

The programs LOOPED1 and LOOPED2 has a FOR structure that divides 10 by every integer from -5 to 5.   (10/-5, 10/-4, etc..)

We can see that the counter will have a problem when the variable reaches 0.  Division by 0 will cause an error and stop execution.  We are going to use BREAK and CONTINUE to mitigate this problem.

LOOPED1 – Break

EXPORT LOOPED1()
BEGIN
// Demonstration: BREAK
LOCAL x,y;
y:={};
// Loop
FOR x FROM −5 TO 5 DO
// Since we can′t
// divide by 0...
IF x==0 THEN
BREAK;
END;
y:=CONCAT(y,{10/x});
END;
RETURN y;
END;

When x=0, the for-loop is stopped.  As a result LOOPED1 returns:
{-2, -2.5, -3.333333333, -5, -10}


LOOPED2 – CONTINUE

EXPORT LOOPED2()
BEGIN
// Demonstration: CONTINUE
LOCAL x,y;
y:={};
// Loop
FOR x FROM −5 TO 5 DO
// Since we can′t
// divide by 0...
IF x==0 THEN
CONTINUE;
END;
y:=CONCAT(y,{10/x});
END;
RETURN y;
END;

In this case when the for-loop encounters x=0, that iteration is skipped and the loop continues.
Result:  {-2, -2.5, -3.333333333, -5, -10, 10, 5, 3.333333333, 2.5, 2}

Eddie


This blog is property of Edward Shore, 2017.

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.