Showing posts with label HP Prime. Show all posts
Showing posts with label HP Prime. Show all posts

Saturday, December 6, 2025

Basic vs. Python: Numeric Guessing Games (Featuring Casio fx-702P and fx-CG100)

Basic vs. Python: Numeric Guessing Games


Calculators Used


Basic: Casio fx-702P

Python: Casio fx-CG100


Task


Generate two simple number guessing games.


Guess the Number


This is the classic guess the number. The game generates a number (positive integer) at random in a given range. The player guess the number and if it doesn’t match the target number, the player is told whether the target number is lower or higher. The objective is to find the target number in the lowest number of turns.


The pricing game, The Clock Game, from the legendary game show The Price Is Right uses the Guess the Number game for two prizes. The Clock Game, the contestant needs to get the three-digit price correct for each prize within a total of 30 seconds, with the host (Drew Carey or the late Bob Barker) informing the contest whether the correct price is higher or lower.


The code is for a game where the target integer is between 10 and 99.


BASIC: Casio fx-702P


10 PRT "GUESS THE NUMBER"

20 T=INT (RAN#*90+10)

30 C=0

40 G=0


100 INP "GUESS (10-99)",G

110 IF G<10 THEN 100

115 IF G>99 THEN 100

120 C=C+1

130 IF G<T;PRT "HIGHER"

140 IF G>T;PRT "LOWER"

150 IF G=T THEN 200

160 GOTO 100


200 PRT "CORRECT! THE # IS ";T

210 PRT "# GUESSES: ";C


PYTHON: Casio fx-CG100

Script: numguess.py


from random import *


print("Guess the number ")

t=int(random()*90+10)

c=0

g=0


# != means not

while t!=g:

  g=int(input("Guess (10-99)? "))

  c+=1

  if g<t:

    print("HIGHER")

  if g>t:

    print("LOWER")


# exact guess leaves the loop


print("CORRECT! The # is "+str(t)+".")

print("# of guesses: "+str(c))


The major difference between the two programs is that the Basic version uses If statements and Goto line statements, while Python code uses a while loop.


Find the Coin


This is a guessing game where the player is tasked to find a coin in a 10 by 10 grid. The rows and columns are labeled 0 through 9.





BASIC: Casio fx-702P


10 PRT "FIND THE COIN ($)"

30 A=INT (RAN#*10)

40 B=INT (RAN#*10)

50 C=0

60 PRT "GRID 0-9,0-9"


70 INP "X (0-9)",X

80 INP "Y (0-9)",Y

90 R=ABS (A-X)

100 S=ABS (Y-B)

105 C=C+1

110 IF R=S THEN 200

120 PRT S;" ROW";R;" COL"

150 GOTO 70


200 PRT "YOU FOUND IT!"

210 PRT "SCORE= ";C


PYTHON: Casio fx-CG100

Script: findcoin.py


# find the coin, 10 x 10 grid


from random import *

print("FIND THE COIN")

# random integer from 0 to 9

a=randint(0,9)

b=randint(0,9)

c=0

print("GRID 0-9,0-9")


# set up 

r=-1

s=-2


while r!=s:

  x=int(input("X 0-9: "))

  y=int(input("Y 0-9: "))

  r=abs(a-x)

  s=abs(b-y)

  c+=1

  if r==s:

    break

  print(str(s)+" rows "+str(r)+" col")


print("You found it!")

print("SCORE= ",str(c))


Note: Both numguess.py and findcoin.py use the random module, hence it can be adopted on every calculator with a random module. The HP Prime’s random module is urandom.


Have fun, and modify as you like,


Eddie


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


The author does not use AI engines and never will.

Sunday, June 8, 2025

HP Prime and TI-84 Plus CE Python: Quartiles of a Data Set

HP Prime and TI-84 Plus CE Python: Quartiles of a Data Set



25th, 50th, and 75th Percentiles


The following code finds five points of a list of data points:


Minimum: the data point of least value

Q1: the first quartile, known as the 25th percentile. The first quartile is median of the lower half of the data.

Median: also known as the 50th percentile, this is the median, or middle point of the data.

Q3: the third quartile, known as the 75th percentile. The third quartile is the median of the upper half of the data.

Maximum: the data point of the most value


The list of data is first sorted in ascending order.


The median is determined as follows:


If the number of data points is odd: Take the number that lies in the middle.

If the number of data points is even: Take the average of the middle two numbers.


The way quartile values are determine vary depending by country and jurisdiction. The program presented uses Method 1, which is used in the United States. (see Source)


If the number of data points is odd: The data is split in half, do not include the median.

If the number of data points is even: The data is split in half.



Python File: quartiles.py, quartile.py


This script does not use any module, so it should work on every calculator that has Python, along with the full-computer editions of Python. Results are shown as floating point numbers, rounded to 5 decimal places.


This was code was made with the HP Prime emulator, and was tested on with an HP Prime, a TI-84 Plus CE Python edition, and a TI-83 Premium CE Python Edition calculator.


# quartiles program

# method 1, median divides data in half

# is used (US method)


# halfway subroutine

def halfway(l):

  n=len(l)

  # get halfway point

  # Python index starts at 0

  h=int(n/2)

  # even

  if n%2==0:

    return(l[h]+l[h-1])/2

  # odd 

  else:

    return(l[h])


print("Use list brackets. [ ]")  

data=eval(input("List of Data: "))


# length of the list

nw=len(data)


# sort the list

data.sort()

print("Sorted Data: "+str(data))


# maximum and minimum

q0=min(data)

q4=max(data)


# get sublists 

h=int(nw/2)

if nw%2==0:

  l1=data[0:h]

  l3=data[h:nw]

else:

  l1=data[0:h]

  l3=data[h+1:nw]


# list check

print("1st half: "+str(l1))

print("2nd half: "+str(l3))

  

# quartiles, q2 is the median

q1=halfway(l1)

q2=halfway(data)

q3=halfway(l3)


# set up  answer strings

txt1=["min = ","Q1 = ","median = ", 

"Q2 = ","max = "]

results=[q0,q1,q2,q3,q4]

for i in range(5):

  txt2="{0:.5f}"

  print(txt1[i]+txt2.format(results[i]))




Examples


Data Set: [1, 2, 3, 4, 5]

Min = 1.00000

Q1 = 1.50000

Med = 3.00000

Q3 = 4.50000

Max = 5.00000



Data Set: [76, 46, 49, 46, 56, 52, 59, 130, 80]

Min = 46.00000

Q1 = 47.50000

Med = 56.00000

Q3 = 78.00000

Max = 130.00000


Date Set: [55, 35, 40, 50, 60, 50, 55]

Min = 35.00000

Q1 = 40.00000

Med = 50.00000

Q3 = 55.00000

Max = 60.00000


Note: A Way to Format Numbers


To format numbers to have a set number of decimal places, use the code

{ identifier : .5f }.


The identifier can be almost anything, I usually call it 0 for the 1st number to be formatted. The number before the “f” (floating point indicator) is the number of decimal places. For example:


2 decimal places: { identifier : .2f }

5 decimal places: { identifier : .5f }

(spaces added for readability)


The text string will need to have a .format(arg) at the end of the string.


Example code:

n = 14.758119

txt = “The rounded value is {0:.5f}”

print(txt.format(n))


returns 14.75812


Source

Wikipedia. “Quartile” Last edited on February 21, 2025. https://en.wikipedia.org/wiki/Quartile Accessed May 12, 2025.



Eddie


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

HP Prime and fx-CG 50: Percentage of a Mortgage Paid

HP Prime and fx-CG 50: Percentage of a Mortgage Paid


Introduction


The program PERMORTGAGE for the HP Prime, and PERMORT for the Casio fx-CG 50 calculates the percentage of mortgage paid off any time during the mortgage’s term.


Inputs:

N = The length of the mortgage (or loan) in number of monthly payments. The payments are assumed to be made at the end of the month.

R = The annual rate of the mortgage. Assume that this loan is fixed.

L = The amount of the loan.

D = The number of payments already made.


Assume that there is no balloon payment.


The % of mortgage paid is calculated by the following steps:


Step 1: Let P by the monthly payment: P = PMT(N, R, L, 0, 12, 12)

(the last two arguments are payments per year and compounding periods per year, both set at 12)


Both calculators featured use the cash flow convention. That is, all cash inflows (receipts) are positive and cash outflows (payments) are negative. In this case, the monthly payment (P) and balance remaining (B) are negative.


Step 2: Let B be the approximate balance using the FV (future value) function:

B = FV(D, R, L, P, 12, 12)


Step 3: Calculate the % of mortgage paid:

T = (1 + B / L ) * 100%



HP Prime Program Code: PERMORTGAGE


Syntax: PERMORTGAGE( nterm, rate, loan, npaid )

nterm = number of monthly payments for the entire term. Example for a 30 year term, nterm = 360

rate = annual rate of a mortgage

loan = loan amount

npaid = number of payments made


Result: % of the principal paid


Code:


EXPORT PERMORTGAGE(nt,rate,loan,np)

BEGIN

// n term, rate, loan,,n paid

// Percent of a Mortgage Paid

// Monthly payments assumed, end mode assumed

// Assume no balloon payment

// EWS 2024-11-01


LOCAL pymt,prct,baln;

pymt:=Finance.TvmPMT(nt,rate,loan,0,12,12);

baln:=Finance.TvmFV(np,rate,loan,pymt,12,12);

// PMT and FV will be negative

prct:=(1+baln/loan)*100;

RETURN prct;

END;



Casio fx-CG 50 Program: PERMORT


The program asks for a single calculation or range of calculations which is stored in Matrix Mat A. (The first row is has two zeros, and is used as a “header”.) The first column is the number of payments made, the second is the percentage of mortgage (loan) paid.


Code:


PmtEnd

“N (TERM)”? → N

“RATE”? → R

“LOAN AMT”? → L

Menu “TYPE”,”SINGLE”,1,”RANGE”,2

Lbl 1

Cmpd_PMT(N,R,L,0,12,12) → P

Cmpd_FV(D,R,L,P,12,12) → B

(1+B÷L)×100 → T

“PERCENT PAID =”

T

Stop

Lbl 2

“N1”? → A

“N2”? → B

“STEP”? → C

[ [ 0 ] [ 0 ] ] → Mat A

For A → D To B Step C

Cmpd_PMT(N,R,L,0,12,12) → P

Cmpd_FV(D,R,L,P,12,12) → B

(1+B÷L)×100 → T

Augment(Mat A, [ [ D ] [ T ] ]) → Mat A

Next

Trn Mat A → Mat A

“IGNORE TOP ROW - “

“ [ N PER ]” ◢

Mat A

Stop



Example


$100,000 loan over 30 years (360 payments). Screen shots were taking with the HP Prime emulator.


Percent of Mortgage Paid Example


Note that the % paid takes on a curve, the later we get into the term, the more principal is paid off. This program can be a demonstration of how amortization works.


Until next time,


Eddie


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

HP Prime CAS: Riemann-Louiville Integral vs Taking the Indefinite Integral Twice

HP Prime CAS: Riemann-Louiville Integral vs Taking the Indefinite Integral Twice



Introduction


The Riemann-Louiville Integral takes the integral of the function f(x) of any positive order v. The integral is defined as:


c_D_x^(-v) = 1 / Γ(v) * ∫( (x – t) * f(t) dt, t = c, t = x)


where:

c = a real constant, which can be zero

f(x) = function of x

t = dummy variable of integration

‘v = order where v >0


If v=1, this is the regular integral. However, the value of v can be a positive non-integer. If v=2, then the Riemann-Louiville integral is a result if you integrate the function twice.


This is one of the formulas on determining indefinite integrals of various orders.



HP Prime CAS Function: dblint


Double Integral of f(x) which takes the integral of f(x) twice. The variable x is used in the function.


dblint(f):= ∫∫ f dx dx


HP Prime CAS Function: rlint


The Riemann-Liouville Integral of f(x). The input has the variable x as the independent variable. The result of the function returns t as the independent variable.


rlint(f,c,v):=(∫(t–x)^(v–1)*f,x,c,t)) / Gamma(v)


Note that the variables x and t are switched to allow the input to be a function of x.


Notes


This was programmed on the CAS page in the format:


func(var) := function


I was not able to use the Program Editor mode at time of programming (July 30, 2024). (Beta Firmware 15048)


Examples



Double Integral: dblint

RLI, v = 2: rlint with c = 0

f(x) = x^m, m>0

x^(m+2) / (m^2 + 3*m + 2)

t^(m+2) / (t^2 + 3*t + 2)

f(x) = a*x + b

(a*x^3 + 3*b*x^2) / 6

(a*t^3 + 3*b*t^2) / 6

f(x) = e^x

e^x

-t + e^t – 1

f(x) = cos x

-cos x

-cos t + 1


Taking the derivative twice will return us back to the original function. Note that the indefinite integral function assumes that the added constant is zero ( ∫ f(x) dx = F(x) + C ).



Source


Kimeu, Joseph M., "Fractional Calculus: Definitions and Applications" (2009).Masters Theses & Specialist Projects. Paper 115. http://digitalcommons.wku.edu/theses/115



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.

Sunday, September 8, 2024

HP Prime and Numworks: Plotting a Parametric Line of Motion

 HP Prime and Numworks: Plotting a Parametric Line of Motion



Plotting the Position of Motion


This program draws a 2D motion plot from an initial starting point (x, y) given initial velocity and acceleration. The rate and direction of both velocity and acceleration are assumed to be constant.

x(t) = ax * t^2 / 2 + vx * t + x0

y(t) = ay * t^2 / 2 + vy * t + y0

where:

t = number of seconds.

ax = acceleration in the x direction

ay = acceleration in the y direction

vx = initial velocity in the x direction

vy = initial velocity in the y direction



The HP Prime PPL program PLOTMOTION displays a traceable curve with a table of values.

The Numworks python script plotmtn.py uses math and matplot.pyplot modules. A scatter plot is laid on top of the path plot. The plot begins at the initial point where it is marked green.



HP Prime Program: PLOTMOTION



EXPORT PLOTMOTION()

BEGIN

// EWS 2024-07-22



LOCAL ch;

ch:=INPUT({C,D,A,B,V,U,N},

"Motion Plot Per Second",

{"x0:","y0:","vx:","vy:","ax:","ay:","n:"},

{"initial x position",

"initial y position",

"initial velocity x direction",

"initial velocity y direction",

"acceleration x direction",

"acceleration y direction",

"number of seconds"});



// user presses cancel

IF ch==0 THEN

KILL;

END;



// user presses OK

STARTAPP("Parametric");



'V*T^2/2+A*T+C'▶X1;

'U*T^2/2+B*T+D'▶Y1;

CHECK(1);



Parametric.Tmin:=0;

Parametric.Tmax:=N;

Parametric.Tstep:=1;



// table and plot

STARTVIEW(10);

STARTVIEW(9);

END;





Numworks Python Code: plotmtn.py


from math import *
from matplotlib.pyplot import *

# 2024-07-23 EWS

print("Motion Plot per second from (0,0)")
c=eval(input("init. x position? "))
d=eval(input("init. y position? "))
a=eval(input("init. x velocity? "))
b=eval(input("init. y velocity? "))
v=eval(input("acceleration x? "))
u=eval(input("acceleration y? "))
n=int(input("number of seconds? "))

x=[v*t**2/2+a*t+c for t in range(n)]
y=[u*t**2/2+b*t+d for t in range(n)]

x0=min(x)-1
x1=max(x)+1
y0=min(y)-1
y1=max(y)+1
axis((x0,x1,y0,y1))
text(x0,y1-1,"Motion Plot")
plot(x,y,'gray')
scatter(x,y,color='blue',marker="h")
scatter(x[0],y[0],color='green',marker="h")
show()





Source

Tremblay, Christopher. Mathematics for Game Developers. Thomson Course Technology. Boston, MA. 2004. ISBN 1-59200-038-X.


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, September 7, 2024

HP Prime: Minimum Distance Between a Point and a Line

HP Prime: Minimum Distance Between a Point and a Line



Introduction


We have a line in the form of y = m * x + b, where m is the slope of the line and b is the y-intercept of the line, and a separate point (px, py). The task is to find the minimum distance, or the shortest distance, between the point and the line. The separate point is not required to be on the line. The line and point are in two-dimensional space.


If the point (px, py) is not on the line, then theoretically, there are an infinite amount of distances between the point and the line. However, to get the shortest distance, draw a path that is “directly straight” to the line. This is achieved by choosing a line that connects the (px, py) that is a line that is orthogonal (perpendicular) to the line y = m * x + b.





The line drawn is of the form y = -1/m * x + b1. The slope of the orthogonal line is -1/m. Assuming that m ≠ 0, the y-intercept of the orthogonal line is b1 = y1 + x1 / m.


The next step is to find where the two lines intersect, which is done by solving the following system for x and y:


y = m * x + b

y = -m / n + b1


Label the intersection point (x1, y1). The minimum distance will be calculated as follows:


dist = √( (x1 – px)^2 + (y1 – py)^2 ) = abs( (x1 – px) + (y1 – py)*i)



If m = 0, the line is in the form of y = b. The orthogonal line is x = px, and the distance is simply abs( (y1 – py)*i ).



HP Prime Code: PTLNDIST


EXPORT PTLNDIST()

BEGIN

// 2024-07-21 EWS



// radian

HAngle:=0;



LOCAL px,py,m,b;



INPUT({m,b,px,py},

"Point-Line Distance (px, py), y=mx+b",

{"m:","b:","px:","py:"},

{"m: slope"," b: y-intercept",

"point x","point y"});



LOCAL y0;

y0:=m*px+b;


LOCAL b1,mt,x1,y1,dist,str;

IF m≠0 THEN

b1:=py+px/m;

mt:=[[−m,1],[1/m,1]]^-1*[[b],[b1]];

x1:=mt[1,1];

y1:=mt[2,1];

dist:=ABS((x1-px)+(y1-py)*√(-1));

ELSE

x1:=px;

y1:=b;

dist:=ABS((y1-py)*√(-1));

END;



// print results

PRINT();

PRINT("Results:");

PRINT("Intersect point:");

PRINT("x: "+STRING(x1));

PRINT("y: "+STRING(y1));

PRINT("");



IF m≠0 THEN

str:="Y="+STRING(-1/m)+"*X+"+STRING(b1);

ELSE

str:="X="+STRING(x1);

END;



PRINT("Orthogonal Line:");

PRINT(str);

PRINT("");

PRINT("Minimum Distance:");

PRINT(dist);



RETURN {x1,y1,str,dist};

END;


Note:


√(-1) represents the imaginary number â…ˆ ( [ Shift ], [ 2 ] ).


Inputs:


* The slope of the y-intercept of the line y = m * x + b (no vertical lines, but m can be zero)

* The point (px, py)


Outputs:


* The line that runs through point (px, yx) that is orthogonal to y = m * x + b. The slope and y-intercept of the orthogonal line, which the line will be stated in a string

* The intersection point of the two lines.

* The distance between (px, yx) and the intersection point. (dist)



Examples


Example 1:

Inputs: Line: y = 5 x – 2, Point: (-1, -5)

m = 5

b = -2

px = -1

py = -5


Results:

Intersect point:

x = -0.615384615386

y = -5.07692307692

Orthogonal Line:

Y = -0.2 * X – 5.2

Minimum distance:

0.392232270274



Example 2:

Inputs: Line: y = 6, Point: (3, -9)

m = 0

b = 6

px = 3

py = -9


Results:

Intersect point:

x = 0.764705882353

y = 4.05882352941

Orthogonal Line:

X = 3

Minimum distance:

15



Example 3:

Inputs: Line: y = 4 x + 1, Point: (5, 3)

m = 4

b = 1

px = 5

py = 3


Results:

Intersect point:

x = 0.764705882353

y = 4.05882352941

Orthogonal Line:

Y = -0.25 * X + 4.25

Minimum distance:

4.36564125066


Source

Tremblay, Christopher. Mathematics for Game Developers. Thomson Course Technology. Boston, MA. 2004. ISBN 1-59200-038-X.


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.

Sharp EL-5200/EL-9000 AER II Program Collection – September 2026

Sharp EL-5200/EL-9000 AER II Program Collection – September 2026 For my review on the Sharp EL-5200 (also known as the Sharp EL-9000)...