Showing posts with label basic. Show all posts
Showing posts with label basic. Show all posts

Sunday, September 13, 2026

HP 71B Basic and Casio fx-CG 100: Weighted Random Sample

HP 71B Basic and Casio fx-CG 100: Weighted Random Sample




Introduction



In calculators, it is fairly easy to generate a random sample when every number or object has an equal chance to be picked. But what happens when this is not the case?


Let’s compare two bags:


Bag A has one red marble, one blue marble, one green marble, and one gold marble.


Bag B has one red marble, three blue marbles, two green marbles, and one gold marble.


Bag A has an equal amount of colored marbles, while Bag B doesn’t.


We could easily use a list to represent Bag B as such:

[red, blue, blue, blue, green, green, gold]


That is well and good when the population is small. Let’s consider a larger population:


Box C has 100 red marbles, 75 blue marbles, 100 green marbles, and 125 gold marbles. If we took the approach like we did with Bag B, we would have a list of 400 elements. Some calculators don’t even allow a list with 400 elements! And if they do, that list might take a lot of memory. This calls for a different approach.



An Approach to Consider



Consider creating a table of cumulative probabilities. Then we can use a standard random number (psuedo)generator function, which generates random number between 0 (inclusive) and 1 (not inclusive).


We will take Box C as an example. Recall that Box C has 100 red marbles, 75 blue marbles, 100 green marbles, and 125 gold marbles.


Calculate the probability of picking only one marble out of the bag.


Color

# of Marbles

Probability

Red

100

0.25

Blue

75

0.1875

Green

100

0.25

Gold

125

0.3125

Total

400



Note that sorting is not required. The next step is to calculate the cumulative probability.


Color

# of Marbles

Probability

Cumulative Probability

Red

100

0.25

0.25

Blue

75

0.1875

0.4375

Green

100

0.25

0.6875

Gold

125

0.3125

1

Total

400




The probability intervals can be set up as:


Red: 0 ≤ x < 0.25

Blue: 0.25 ≤ x < 0.4375

Green: 0.4375 ≤ x < 0.6875

Gold: 0.6875 ≤ x < 1


General a random number, for example: 0.344. Since 0.344 lies in between 0.25 and 0.4375, this corresponds to a blue marble.


Let’s say the random number is 0.678. Since 0.678 lies in between 0.4375 and 0.6875, this corresponds to a green marble.



The HP 71B Basic Problem WSAMPLE


The program is uses a container of four colored marbles: red, blue, green, and gold. Provide the number of marbles for each color and the sample size. Each pick is shown to be separately noted on paper or computer.


Note that this a sample with replacement (whatever is picked is returned to the population, which could allow repeats).


Code (365 bytes):


100 DESTROY ALL

105 OPTION BASE 1

110 DIM S$(4)[5]

115 DIM W(4)

120 S$(1)="RED"

125 S$(2)="BLUE"

130 S$(3)="GREEN"

135 S$(4)="GOLD"

140 DISP "# OF MARBLES?" @ WAIT .5

145 T=0

150 FOR I=1 TO 4

155 DISP S$(I) @ WAIT .5

160 INPUT W(I)

165 T=T+W(I)

170 NEXT I


200 U=0

205 DISP P(4),C(4)

210 FOR I=1 TO 4

215 P(I)=W(I)/T

220 U=U+P(I)

225 C(I)=U

230 NEXT I


300 INPUT "SIZE? ";N

305 FOR I=1 TO N

310 R=RND

315 J=1

320 X=C(J)

325 IF R>=X THEN 400

330 DISP STR$(I)&": "&S(J) @ PAUSE

335 NEXT I

340 END


400 J=J+1

405 GOTO 320



Examples (results will vary):


Example 1: (n = 5)

1: GREEN

2: RED

3: GOLD

4: RED

5: GREEN


Example 2: (n = 5)

1: BLUE

2: GREEN

3: GREEN

4: RED

5: GREEN


Example 3: (n = 10)

1: RED

2: GOLD

3: BLUE

4: BLUE

5: GREEN

6: GREEN

7: GOLD

8: RED

9: RED

10: GREEN



Casio fx-CG 100 Python: Weighted Random Sample



This program script, wsample.py, asks for a list of labels and the population for each label. This allows flexibility for additional applications.


Note that this a sample with replacement (whatever is picked is returned to the population, which could allow repeats).


Code:



# EWS 2026-09-05

from math import *

from random import *


print("Weighted Random Sample")

s=eval(input("Label List? "))

w=eval(input("Weights List? "))

n=int(input("Sample Size? "))


# determine probabilities

p=[i/sum(w) for i in w]


# cumulative sums

c=[sum(p[:i+1]) for i in range(len(p))]


# build sample

x=[]

for i in range(n):

  r=random()

  i=0

  while r>=c[i]:

    i+=1

    # end while

  x.append(s[i])

  # end for  


print(x)



Example (results will vary):


Example 1:

labels: [“red”, “blue”, “green”, “yellow”]

weights list: [ 5, 15, 10, 5 ]

sample size: 10

result: [“yellow”, “green”, “green”, “blue”, “yellow”, “green”, “yellow”, “green”, “red”, “green”]


Example 2:

labels: [“purple”, “orange”, “teal”, “gray”, “mint”]

weights list: [10,20,10,10,20]

sample size: 10

result: [“mint”, “gray”, “teal”, “purple”, “orange”, “purple”, “gray”, “mint”, “orange”, “orange”]



Hopefully this approach is useful.


Eddie


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

BASIC vs. Python: Mean and Standard Deviation by an Iterative Method

BASIC vs. Python: Mean and Standard Deviation by an Iterative Method



Calculators Used:

BASIC: Sharp EL-5500 III

Python: Casio fx-CG 100


Introduction


The following code calculates the sum, mean, and standard deviation of a data set. The method that will be used is from voidware.com, which suggests an iterative method, as follows (Voidware):


M_0 = 0, S_0 = 0, n = 0


Loop with data point X:

M_n+1 = M_n + (X – M_n) ÷ (n + 1)

S_n+1 = S_n + (X – M_n) × (X – M_n+1)

n = n + 1


When all the data as been tabulated:

S = √(S ÷ (n – 1))


M: mean

S: standard deviation


Source

“Standard Deviation” Voidware. http://www.voidware.com/sd.htm Website was last updated in 2018. Last Retrieved July 4, 2025.



BASIC: Sharp EL-5500 III



10 PRINT "ONE VAR STATS"

12 CLEAR

30 INPUT "DATA? "; X

32 E=M+(X-M)*(N+1)

34 S=S+(X-M)*(X-E)

36 N=N+1

38 M=E

40 U=U+X

42 INPUT "MORE? (1=YES) "; C

44 IF C=1 THEN 30

60 S=√(S/(N-1))

70 PRINT "# DATA= "; N

72 PRINT "SUM= "; U

74 PRINT "MEAN= "; M

76 PRINT "STD DEV= "; S

78 END



Notes:

CLEAR: clears all the variables A-Z and resets their values to zero

PRINT: pauses the screen while the message is displayed



Python: Casio fx-CG 100

(Can be we used with any calculator with Python)



# one var stat without the math module

# voidware.com/sd.htm



def onevar(data):

  # set up

  m,s,u,n=0,0,0,0

  for i in data:

    e=m+(i-m)/(n+1)

    s+=(i-m)*(i-e)

    n+=1

    m=e

    u+=i

  s=(s/(n-1))**0.5

  return [n,u,m,s]



Notes:

We can store multiple values to variables at once. Example:

var4, var3, var2, var1 = value1, value2, value3, value4



Storage Arithmetic:

s+=expression -> s=s+expression

s-=expression -> s=s-expression

s*=expression -> s=s*expression

s/=expression -> s=s/expression



Example



Data set:

n = 1: x = 105

n = 2: x = 107

n = 3: x = 86

n = 4: x = 96

n = 5: x = 113



Data Structure: [105, 107, 86, 96, 113]



Results:

# DATA: 5 (N)

SUM: 507 (U)

MEAN: 101.4 (M)

STD DEV: 10.54988151 (S)


Eddie


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



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.

Saturday, November 15, 2025

Basic (TI-81) vs. Python (TI-84 Plus CE Python): First and Second Derivative and Integral by Simpson’s Rule

Basic vs. Python: First and Second Derivative and Integral by Simpson’s Rule



Calculators Used


Basic: TI-81

Python: TI-84 Plus CE Python



Task


Estimate the numerical first derivative by the Nearby Secant Line Method:


f'(x) = lim (f(x + h) - f(x - h)) / (2 * h) as h → 0



Estimate the numerical second derivative by:


f''(x) = lim (f(x + h) - 2 * f(x) + f(x - h)) / h^2 as h → 0



Estimate the definite integral by Simpson’s rule:


∫( Y1 dx, x = a to x = b) ≈

(b - a)/(3 * n) + (f(a) + 4 * f1 + 2 * f2 + 4 * f3 + 2 * f4 + ... + 2 * f_n-2 + 4 * f_n-1 + f(b))


n must be an even integer.

fi = f(a + i * (b – a) / n)


BASIC: TI-81


First let’s look at the TI-Basic version with the classic TI-81:


First Order Derivative  (Nearby Secant Line Method)


f'(x) ≈ (f(x + h) - f(x - h)) / (2 * h)


DER1  (61 bytes)

Function

Rad

Disp "D/DX Y1"

1E-4 -> H

Disp "X?"

Input A

A+H -> X

Y1 -> D

A-H -> X

(D-Y1)/(2H)->D

Disp D



Second Order Derivative


f''(x) ≈ (f(x + h) - 2 * f(x) + f(x - h)) / h^2


DER2  (75 bytes)

Function

Rad

Disp "D²/DX² Y1"

1E-4 -> H

Disp "X?"

Input A

A+H -> X

Y1 -> D

A -> X

D-2*Y1 -> D

A-H -> X

(D+Y1)/(H^2) -> D

Disp D


INTGY1  (134 bytes)

Function 

Rad

Disp "SIMPSONS RULE"

Disp "A,B,N?"

Input A

Input B

Input N

A -> X

Y1 -> S

B -> X

S+Y1 -> S

1 -> I

Lbl 1

A+I*(B-A)/N -> X

S+2*Y1 -> S

If Fpart (I/2)≠0

S+2*Y1 -> S

IS>(I,N-1)

Goto 1

S*(B-A)/(3*N) -> S

Disp S


Examples


f(x) = 3*x^3 + 4*x – 1


Y1 = 3 * X³ + 4 * X – 1

f’(2.4): DER1 returns: 55.84

f’’(2.4): DER2 returns: 43.2


∫( 3 * X³ + 4 * X – 1 dX, 0.5, 1.5):

INTGY1 returns with N = 40 returns 6.75


Notes for BASIC


Before running the programs, store the function to the variable Y1. Calling Y1 evaluates the function of the value stored in variable X. Evaluate Y1 at X: [2nd], (Y-VARS), 1


The TI-81 MUST be in Function mode to evaluate Y1, unless an error occurs. The programs set the angle mode to Radians. The value of h is set to a "default" value of 10^-4. We want h to be small, but not too small. A value of h too small can run the risk of floating point errors.


In the integral program:


* I/2 - Ipart (I/2) is Fpart(I/2), but the long way. Python does not have a built-in fractional part function.


* IS>(I,N-1) translates to:


I=I+1

If I>N-1

Goto 1


IS> is the increment (by 1) and skip, a command in TI-Calculator Basic.


In general BASIC languages, evaluation Y1 may take a different approach, depending on the calculator, pocket computer, or computer:


General Basic:


### ...

### X = g(A)

### GOSUB ***

### ...


*** Y = <evaluate f(X)>

*** RETURN


Another approach on a calculator: Use another program


Prog <main>

...

g(A) -> X

Prog "FX" (see below, answer is stored in Y)

...


Prog "FX" (or any name of your choosing)

<evaulate f(X)> -> Y

<end program, an implied Return is executed here>



PYTHON: TI-84 Plus CE Python Edition


The code presented here uses the math module and built-in functions, and should work with any calculator with Python.


DERINTG.py


from math import *

# derivatives and integrals

# 2025-06-01


print("MATH MODULE IS IMPORTED")


# first derivative function

def der1(fx,x,h=1E-3):

  # fx is a string

  # h is optional (def 1E-3)

  # set up lambda

  f=eval("lambda x:"+fx)

  d=(f(x+h)-f(x-h))/(2*h)

  return d


# second derivative function

def der2(fx,x,h=1E-3):

  # fx is a string

  # h is optional (def 1E-3)

  # set up lambda

  f=eval("lambda x:"+fx)

  d=(f(x+h)-2*f(x)+f(x-h))/(h**2)

  return d


# integrals by simpsons rule

def intg(fx,a,b,n=64):

  # fx is a string

  # n is even, optional (def 64)

  # set up lambda

  f=eval("lambda x:"+fx)

  s=f(a)+f(b)

  for i in range(1,n):

    w=f(a+i*(b-a)/n)

    s+=(2*w) if (i/2-int(i/2)==0) else (4*w)

  s*=(b-a)/(3*n)

  return s


I decided to make a script of three functions.


Python uses binary arithmetic, so be prepared to possibly see answers such as 2.999999999999 and 5.00000000000001. The code leaves the answer in floating point form. Feel free to use the round function and/or format specifiers as you see fit.


f(x) = 3*x^3 + 4*x – 1


In Python:

f(x) = 3*x**3+4*x-1


Examples


Store the string to s:

s=”3*x**3+4*x-1”

der1(s,2.4) returns 55.84000299999303

der2(s,2.4) returns 43.19999999324864

intg(s,0.5,1.5) returns 6.75



I hope you find this useful. Enjoy,


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.

TI-84 Evo BASIC: Hydraulic Radius and Chezy-Manning (Circular Pipes)

TI-84 Evo BASIC: Hydraulic Radius and Chezy-Manning (Circular Pipes) Introduction The program, HYDRAD makes three calculations...