Showing posts with label loops. Show all posts
Showing posts with label loops. Show all posts

Sunday, September 15, 2024

Numworks: Allowing Repeated Calculations in Python

Numworks: Allowing Repeated Calculations in Python



Introduction


Say we want the user to repeat a calculation or a routine for as long as the user wants. At the end of each calculation, the user is asked if they want another calculation. The user enters one of two possibilities:


1 for an additional calculation

0 for no more calculation


A flag variable is set up with a default value of 1. As long as this value remains at 1, the calculation repeats.


Scrip structure (I named this variable rptflag, but it can be any name):


rptflag=1


while rptflag!=0:

  …

  < insert inputs and show results >

  …

  print(“Again? No = 0, Yes = 1”)

  rptflag=eval(input())


Entering 0 for the Again? Question exits the loop. We need the eval (evaluate) or int (input) because leaving the input command alone defaults the input to a string.


For the sample scripts below, the escape velocity off the surface of planets and other celestial objects are calculated.


Repeated Loop: General


This script does not require any special modules.


Script: rptdemo1 (We can use this on any calculator or platform)


from math import *


# repeat demonstration 

# set up repeat flag

rptflag=1


while rptflag!=0:

  print("ESCAPE VELOCITY")

  m=eval(input("Mass (kg)? "))

  r=eval(input("Radius (m)? "))

  v=sqrt(1.33486e-10*m/r)

  print("Velocity: ",v,"\nm/s")

  print("Again? no=0, 1=yes")

  rptflag=eval(input())




Repeated Loop: Numworks – using the keyboard


Instead of having the user enter 0 or 1, the user presses the keys 0 or 1. To allow the user key presses, use the Ion module. KEY_ZERO is for the 0 key and KEY_ONE is for the 1 key.


To make the screen look presentable, I’m clearing the screen. This is accomplished by the use of the Kandinsky module. The use of the Kandinsky module was suggest to me on Reddit by Feeling_Walrus3033, and I give credit and gratitude for the suggestion.


The line:


fill_rect(0,0,320,240,(255,255,255)) creates a blank white screen.


Clearing the screen this way will call for a way to display text on the screen. Unfortunately the print() command won’t do it. Kandinsky comes to the rescue with the draw_string command. The syntax for the draw_string command is:


draw_string(“text” or variable containing the string, x pixel, y pixel, [text color], [background color])


Colors are optional. The default is black text on white background.


Keep in mind that using this method will require more memory.


Script: rptdemo2 (Specific to Numworks, for other platforms and calculator, check your specific manual)


from math import *

from ion import *

from kandinsky import *

# repeat demonstration 


# set up keys

def key():

  while True:

    if keydown(KEY_ZERO):

      return 0

    if keydown(KEY_ONE):

      return 1


# set up repeat flag

rptflag=1


while rptflag==1:

  print("ESCAPE VELOCITY")

  m=eval(input("Mass (kg)? "))

  r=eval(input("Radius (m)? "))

  v=sqrt(1.33486e-10*m/r)

  

  # build strings

  s1="Velocity: "+str(v)+" m/s"

  s2="Again? no=0, 1=yes"

  fill_rect(0,0,320,240,(255,255,255))

  draw_string(s1,0,0)

  draw_string(s2,0,20)

  rptflag=key()


draw_string("DONE",0,40,(255,0,0))



Sample Data to Try



Mass (kg)

Radius (m)

Escape Velocity (m/s)

Earth

5.972168E24

6378.137E3

11179.88618486758

Jupiter

1.8982E27

71492E3

59533.32250562

Sun (Solar System)

1.9885E30

6.957E8

617688.6988877566


E: [ ×10^x ] button, shown as “e”



Note: I will be in Nashville for the 2024 HP Handheld Conference on September 21-22, 2024. The next scheduled post will be on September 28, 2024.


Take care,


Eddie


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



Saturday, August 17, 2024

TI-84 Plus CE Python: Diophantine Books Problem and Circles Inscribed in Squares

TI-84 Plus CE Python: Diophantine Books Problem and Circles Inscribed in Squares



Introduction


The two programs presented today are Python versions from the Idea Book (Ahl – see Source), where the original programs were posted in BASIC designed for the Texas Instruments computers in the 1980s. The Python versions were programmed with the TI-84 Plus CE Python (and should work on the TI-83 Premium Python Edition). Unfortunately, the Circle and Squares program may not work on the TI-82 Advanced Python as that calculator does not have any graphics modules.



Diophantine Books Problem


A book store studies the sales of three popular books: A, B, and C, each with prices PA, PB, and PC. We have the total books sold, the sales amount, and the prices of the books. How many of each books were sold?


The program solve the Diophantine system of equations:


A + B + C = N

PA * A + PB * B + PC * C = S


N = number of books sold

S = total sales

A, B, and C are positive integers


The original BASIC program covered a specific case, where in this version has the user enter the price of up to three books, total sales, and number of books sold. The code in Python also counts the number of solutions.



Code: books.py


# Math Calculations

from math import *


# Browns Books, pg 43

# TI HOME IDEA BOOK, 1983

# Translated to Python



print("Browns Books","\na+b+c=n","\npa*a+pb*b+pc*c=s")

print("books: a, b, c","\nbook prices: pa, pb, pc")

n=int(input("# books sold? "))

s=eval(input("total sales? "))

pa=eval(input("price of book a? "))

pb=eval(input("price of book b? "))

pc=eval(input("price of book c? "))


print("Prices: ","\n",pa,"\t\t",pb,"\t\t",pc)

print("-----------------")


# prices

i=0


for a in range(1,n+1):

  for b in range(1,n+1):

    for c in range(1,n+1):

      if a+b+c==n and pa*a+pb*b+pc*c==s:

      print(a,"\t\t",b,"\t\t",c)

      i+=1


print("\n",i," solutions")





Circles In Squares




The program cirsqu.py calculates four areas:


The area of a square with a side of length of 2 * r.

The area of the inscribed circle with radius r.

The trapped area, which is the area of the square not taken up by the circle.

A corner of the area of the square not taken up by the circle, which is 1 / 4 of the trapped area.


The original program only printed the trapped area and the corner area. In addition, this Python code uses TI-specific modules, ti_system and ti_draw.


The ti_system module is used to temporarily stop execution with the disp_wait() command. Execution continues with by pressing the [ clear ] key.


The ti_draw module is used to draw the square, the circle, and the axis. Both the square and circle are centered at (0,0).


The code uses a scaling routine based on the radius of the circle, so that squares look like squares and circles look like circles. The TI-84 Plus CE Python graphics screen is 320 x 220 pixels. Setting up the window (xmin, xmax, ymin, and ymax) using the ratio will accomplish this task. Here are sampling of viewing windows to try:


xmin = -8, xmax = 8, ymin = -5.25, ymax = 5.25


xmin = -16, xmax = 16, ymin = -10.5, ymax = 10.5


xmin = -32, xmax = 32, ymin = -21, ymax = 21


About the fill_rect and draw_rect commands. The syntax is (x, y, width, height). The coordinates x and y are supposed to be the upper left hand corner, however the manual is incorrect in practice. The correct corner to use is the lower left hand corner. The OS that was used is 5.8.1.0012 (same number for Python).


Code: cirsqu.py


from math import *

from ti_system import *

from ti_draw import *


print("Math Module Activated")

print("Circle inside a Square")

print("circle of radius r")

print("square of side r")

r=eval(input("r? "))


ac=pi*r**2

asq=(2*r)**2

ad=asq-ac


# ti system

disp_clr()


print("Radius: ",r)

print("Areas: \nsquare:",asq)

print("circle: ",ac)

print("trapped: ",ad)

print("1/4 trapped: ",ad/4)

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

# ti module ti_system

disp_wait()


# use ti module ti_draw

clear()

# text factor

f=1

# window set up

if r<=5.25:

  x=8

  y=5.25

else:

  y=5.25

  while y<r:

    y*=2

    f*=2

  x=y*8/5.25


set_window(-x,x,-y,y)


# draw axis

set_color(235,235,235)

set_pen("thin","dotted")

draw_line(-x,0,x,0)

draw_line(0,-y,0,y)



# draw shapes

set_color(25,125,255)

set_pen("thin","solid")

# fill_rect anchors at the LOWER-left hand corner (manual error)

fill_rect(-r,-r,2*r,2*r)

set_color(230,130,0)

fill_circle(0,0,r)

set_color(0,0,0)

draw_text(-x,y-2*f,str(y))

draw_text(x-4*f,-y,str(x))

show_draw()




Source


Ahl, David H. The Texas Instruments Home Computer Idea Book. Creative Computing Press. Morris Plains, New Jersey. 1983. pg. 34-35, 105-106 ISBN 0-916688-51-8



Enjoy!


Eddie


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

Monday, May 8, 2023

Retro Review: Casio fx-3900Pv

Retro Review:  Casio fx-3900Pv





Quick Facts


Model:  fx-3900Pv

Company:  Casio

Years:  late 1980s - early 1990s

Type:  Finance

Batteries: 1 x CR-2025

Display:  2 lines

Memory Registers:  1 independent with 6 constant registers

Operating System:  Algebraic 



Programming With Editing!


The fx-3900Pv has a programming module similar to the Casio fx-3600P, its many variations and Radio Shack EC-4004.   What separates the fx-3900Pv from the rest is the inclusion of an editing mode.   


The display has two lines.   The top line has all the mode indicators and program steps. The bottom line is the numeric display.  


We are not programming in the blind.  Yay!


Run Mode:   We execute programs in this mode. [ MODE ] [ . ]


Learn (LRN) Mode:  We enter programs from scratch.   [ MODE ] [ EXP ]


Edit Mode:  We edit programs stored in memory.  New entries are automatically inserted.   Program steps can be deleted by the [ SHIFT ] [ ↑ ] (CLR) key sequence.  [ MODE ] [ 0 ]


There are four program slots.  P3 is the shifted program of P1 and P4 the shift of P2.  


The programming commands available on the fx-3900Pv are:


ENT:  prompts the user for a number.  When entering a program, include a valid number after the ENT command.  The number entered after ENT is not counted as a program step.   


HLT:  Halts program execution.  In run mode, continue exection with the [ RUN ] key.


RTN:  Halts the program execution and returns to the first step.  The RTN instruction allows for repeated calculations.


x>0:  If the number in the display at the time is positive, the program returns the first step.   Otherwise, go to the next step.


x≤M:  If the number in the display is less than or greater than the value stored in memory M, go to the first step.  Otherwise, go to the next step.


A sample program:  


f(x) = x^3 - x^2 ÷ 4 + 1


We will use the first program slot.


P1:

SHIFT:  Min    (store in Memory M)

x^y

-

MR   

SHIFT:  x^2

÷

4

+

1

=


f(2.2):  2.2 [ P1 ].   Result:  10.438

f(-1.9):  1. 9 [ +/- ] [ P1 ].  Result:  -6.7615



Integration  ∫dx


In the integration mode ( [ MODE ] [ 1 ]), we can designate one of the four program slots to approximate a definite integral using Simpson's Rule.  Memory M is used for x in f(x).   The program must start with a Min command and end in equals.  


To calculate the integral:


1.  Enter integral mode.

2.  Pick which program has f(x):  P1, P2, P3, or P4.

3.  Optional:  enter n to specify 2^n divisions, then press [ SHIFT ] [ RUN ].

4.  Enter the lower limit, press [ RUN ], enter upper limit, press [ RUN ].



Example:   ∫ x^3 - x^2 ÷ 4 + 1 dx for x = 1 to x = 5.  Use 16 divisions (n = 4)


[ MODE ] 1 [ P1 ]  (see the section above)

4 [ SHIFT ] [ RUN ]  (display: 16)

1 [ RUN ] 5 [ RUN ]


Result:  1.496666667 * 10^2


(2^8: 256 divisions returns 1.496666665 * 10^2 , after short while)


The integration updates the memory registers as such:


K1 = a

K2 = b

K3 = 2^n

K4 = f(a)

K5 = f(b)

K6 = integral



Other Features


The other modes of the fx-3900Pv are:


Mode 2:  LR.  Linear Regression.  Fits data to the line y = A x + B.


A:  slope

B:  intercept

r:  correlation


K1 = Σx^2

K2 = Σx

K3 = n

K4 = Σy^2

K5 = Σy

K6 = Σxy


Mode 4:  Degrees angle mode


Mode 5:  Radians angle mode


Mode 6:  Gradians angle mode


Mode 7:  Fix point display mode.  To round numbers to the fix point internally, execute the RND (round) command.  

 

Mode 8:  Scientific notation display mode


Mode 9:  Norm mode (floating point)



Registers


[ Kin ]:   Stores the number into any register K1 through K6.


[ Kout ]:  Recalls the value of K1 and K6.


The M register:  < Min >, [ M+ ],  < M- > , [ MR ].


Storage arithmetic:  [ Kin ] followed by [ + ], [ - ], [ × ], [ ÷ ]



Final Thoughts


The fx-3900Pv improves on the fx-3600P programming module by adding an editing mode. 


Missing from is the fractions and fraction-decimal conversions.   I would have loved to see other programming commands such as integer part, functional parts, and absolute value.   Other than that, the fx-3900Pv is a big improvement of the fx-3600P.


Casio Ledudu page of fx-3900Pv: 

https://casio.ledudu.com/pockets.asp?lg=eng&type=417



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. 


Monday, May 30, 2022

Plus42: The FOR Function

Plus42:  The FOR Function



About the Plus42 App


Author:  Thomas Okken


App: 

Android:  $9.99

iOS:  $9.99

PC/MacOS/Linux:  Free

Donations Accepted


Link:  https://thomasokken.com/plus42/


Please give Okken some love!   Free42 and Plus42 are both awesome apps and emulators, both emulate the HP 42S engine.  The Plus42 adds the solver of the HP 17B/19B/27S and unit conversions of the HP 48/49/50 family.   The Plus42 can also graph functions.   You can find a lot more information on the link above!


(Disclaimer:  I am not being paid.)


I am now including apps like the Plus42 in my rotation for blogs, please be on the look out for those.  


Today's blog entry will cover one of the additional solver functions for the Plus42:  FOR.


Plus42 FOR Syntax


FOR(INIT:COND:NEXT:EXPR)


INIT:  Initial commands


COND:  condition

If the condition is true:  execute EXPR (there can be more than one EXPR statements), then NEXT

If the condition is false:  the loop ends


NEXT:  next command,  this is where the counter variable is incremented or decremented


EXPR:  the main loop


Examples 


Example 1:  Add from 1 to 4.


HP 39G/Prime Code:

A:=0;

FOR K FROM 1 TO 4 DO  (STEP 1)

A:=A+K;

END;


Plus42 Equation Code:

S=FOR((L(A:0)+L(I:1))×0:G(I)≤4:L(I:G(I)+1):L(A:G(A)+G(I)))


Variables:

S = sum_final answer

A = sum

I = counter variable


Result:  S = 10


S=:   set the result to the variable S, S = A

INIT:  (L(A:0)+L(I:1))×0;  set A = 0 and I = 1

COND:  G(I)≤4;  test if I≤4; if true continue, if false exit the loop

NEXT:  L(I:G(I)+1); this happens at the end of the loop, this is like the general STEP incr/decr command

EXPR: L(A:G(A)+G(I))


The use of the Get function allows the variable to used automatically and not be displayed in the CALC menu.  


Something that threw me off is that the order of NEXT and EXPR, which the EXPR (which I think there could be more than one EXPR statements), I am used to NEXT either at the end of the FOR loop or implied (end of indentation in Python, for example).


Example 2:  Product


Calculate Π(n/4, n=1 to m) = 1/4 * 2/4 * 3/4 * ... * m/4


Plus42 Equation Code:

P=FOR((L(A:1)+L(N:1)+M)×0:G(N)≤IP(M):L(N:G(N)+1):L(A:G(A)×(G(N)÷4)))


Variables:

P = product_final answer

N = counter

M = higher limit


P=:   set the result to the variable P, P = A

INIT:  (L(A:1)+L(N:1)+M)×0; set A = 1, N = 1, ask for M

COND: G(N)≤IP(M); if N ≤ IP(M); if true continue, if false exit the loop

NEXT:  L(N:G(N)+1)

EXPR: L(A:G(A)×(G(N)÷4))


Results:

3 → M; P → 0.0938

6 → M; P → 0.1758

12 → M; P → 28.5507


Example 3:  Recursive


Given an initial condition u_0, calculate the recursion:


u_n = 2 * u_n-1 - 3


for n terms.


Plus42 Equation Code:

S=FOR((U+N+L(I:1))×0:G(I)≤N:L(I:G(I)+1):L(U:2×G(U)-3))


Variables:

S = final answer

U = recursive variable

N = number of terms


S=:  final answer

INIT:  (U+N+L(I:1))×0

COND: G(I)≤N

NEXT:  L(I:G(I)+1)

EXPR:  L(U:2×G(U)-3)


Results, enter U, N first before calculating for S:

2 → U, 3 → N; S → -5

5 → U, 2 → N; S → 11


Enjoy and hope this helps,


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. 

Monday, February 14, 2022

Retro Review: Casio fx-4000P

Retro Review:   Casio fx-4000P





Quick Facts:


Model:  fx-4000P

Company:  Casio

Years:  1985 - 1989

Battery:  2 x CR2032

Display:  10 digits, 2 digit exponent

Logic:  Algebraic - type in expressions the way you write them

Memory:  Up to 550 programming steps or up to 94 memory registers

Contrast Wheel

Wallet with operation guide (if included, depends on where you buy from)


The Casio fx-4000P holds up its value as it is a popular vintage programming calculator. Prices are about $30 US and above.  

 

Features


Four Basic Modes:


* COMP:  Computer Mode, general calculations


* BASE-n:  Base conversions in the standard four bases decimal, binary, octal, and hexadecimal.  Boolean functions and, or, not, and neg are included.   Binary numbers have a 32 bit capacity, in 4 blocks of 8 each.  


*  SD:  Single Variable statistics


*  LR:  Linear Regression, y = A + Bx


Statistics Variables:

U = Σx^2

V = Σx

W = n

P = Σy^2

Q = Σy

R = Σxy


A = y-intercept

B = slope

r = correlation


As with many Casio calculators, the rectangular and polar conversions store their results in two variables.   For the fx-4000P:


Pol(x,y) stores r in I, Θ in J

Rec(r,Θ) stores x in I, y in J


This is the same as the Casio current fx-5800P.  


The fx-4000P has integer part (Int), fractional part (Frac), and absolute value (Abs).  


Memory and Arrays


The Defm mode allows the user to set the number of memory registers.   The minimum amount of memory registers is 26 (A - Z).   The user can add additional registers at a cost of 8 programming steps each, up to 94 memory registers (leaving only 6 programming steps).   


The fx-4000P allows for indirect storage, which takes the form of:


letter[# of steps from that letter]


For example:

A[0] returns what is stored in A,

A[1] returns what is stored in B,

A[2] returns what is stored in C,

and so on.


By allocating additional registers, 

Z[1] returns what is stored in the 27th register,

Z[2] returns what is stored in the 28th register,

Z[3] returns what is stored in the 29th register,

and so on. 


Variables are allowed.  For example, if 2 is stored in I,  then:


15 → A[ I ] stores 15 in C (2 steps from A).

  

The tilde command is allows us to store a value in multiple registers.  The tilde acts like a Fill function.


For example:  12 → A ~ D  stores 12 in A, B, C, and D.  


Programming


The programming mode of the fx-4000P has a capacity of 550 steps, which can be allocated into 10 slots, Prog 0-9.   The maximum step capacity is reached when the minimum of memory registers is set, 26.  (Defm 0).  The language is Casio Basic:


:

colon that ends each line (except for ◢)


→   

store 


◢  

stop and display (Disp indiciator lights up)


Goto/Lbl #   

up to 10 lables 0-9


Isz var  

increment var by 1 and skip next command if var = 0


Dsz var

decrement var by 1 and skip next command if var = 0


Use Isz and Dsz to simulate For-Next loops


[test]  ⇒ [do if true, skip if false] : [ next command ]

simple If/Then jump structure (displayed on the keyboard is a solid, bold arrow)


Prompting is a little different, as the string must be followed by a colon, then a question mark is used:

"prompt" : ? → var


Example:   Prompt for the user to enter an angle and store it A.   

"ANGLE" : ? → A


We can display a string for a brief pause, simulating a Wait command by this:

"time" → var : Lbl # : "string" : Dsz var : Goto # 


For example, the string "45" is displayed for 25 counts:

25 → I : Lbl 1 : "45" : Dsz I : Goto 1


Strings can also contain the characters engineering symbols k, m, μ, n, p (but not use these in calculations), a solid square, and the angle symbols °, ^r, and ^g (which also allow the user to override the current angle). Strangely, the symbols Θ and % are not included.  


The use of Prog (key is labeled [Prg]) in programs will allow for the use of subroutines.  For subroutines, an implied Return command is added to the end of the subroutine.  


To save space, use → without closing all the parenthesis.  The Ans (last answer) can also be used in between steps.   In COMP mode, pressing equals closes all pending parenthesis.  


The programming structure of the fx-4000P, along with the fx-7000g and fx-6300g,  provide a base for future Casio programming and later graphing calculators.  


Sample Programs:

(spaces and returns provided for readability)


PO:  Σ( (A*x+B)^C from x = 0 to N )

(65 steps)


"A" : ? → A :

"B" : ? → B :

"C" : ? → C :

"N" : ? → N :

0 → S :

Lbl 1 :

S + (A N + B) x^y C → S

Dsz N : Goto 1 : 

S + B x^y C → S


Examples: 

A = 2, B = 6, C = 2, N = 4;  Result = 540

A = 5, B = -2, C = 3, N = 5;  Result = 20727


P1:  Payment of a Mortgage

(64 steps)

P = loan amount

R = periodic rate

N = number of payments

M = payment 

Cash flow convention is followed.


Fix 2 :

"PV" : ? → P :

"RATE" : ? → R :

"N" : ? → N :

.01 R → S :

"PMT" ◢

-P S ÷ (1 - (1 + S) x^y ( -N → M ◢

Norm


Example:

Monthly payment of a $320,000.00 loan at 4% annual for 30 years.

P = 320000, R = 4 ÷ 12, N = 30 × 12; Result -1527.73  (payment of $1,527.73)


If you want to a series of programs for the fx-4000P and possible what they would look like for the fx-5800P/graphing calculators, please let me know in the comments. 


Closing Thoughts


The Casio fx-4000P is a good, entry level programmable calculator which includes a good amount of programming steps.  


The fx-4000P reminds me of the current Casio fx-3650P(II) and what the latter lacks.   I wish the next incarnation of the fx-3650P had the integer, fractional, absolute value, and the ability to use strings with the full alphabet.   The only advantage the fx-3650P has is the derivative, integral, and fractions. 


The fx-4000P runs decently fast and the screen has a big display of characters and results, and it holds up as a favorite.  


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. 



RPN: DM32 and DM42: Stopping Sight Distance (Metric)

RPN: DM32 and DM42: Stopping Sight Distance (Metric) The Stopping Sight Distance Formula – Derivation The stopping sight di...