Showing posts with label Python. Show all posts
Showing posts with label Python. 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, September 5, 2026

Python – Earth’s Radius and Gravity in US Units

Python – Earth’s Radius and Gravity in US Units



Introduction



The following script, gravus2.py, estimates the Earth’s gravity in ft/sec^2 given:



1. The observer’s latitude on Earth (North or South; you don’t have to enter negative numbers for South)

2. The elevation where the observer is in feet.



The Python script is made with a TI-84 Evo, but it should work with all platforms with Python.



Equation Used: With Everything Converted to U.S. Units:



Calculating g_0 at sea level with latitude φ:

g_0 = 32.17192 – 0.08530 * cos(2 * φ°) = 32.17192 – 0.08530 * cos(2 * φ * Ï€ ÷ 180)



Calculating g_h with height h:

g_h = g_0 * (erad ÷ (erad + h ÷ 5280))^2



Where (Earth’s radius at latitude φ):

erad = √((a^4 + b^4 * tan(φ)^2) ÷ (a^2+ b^2 * tan(φ)^2)) 



a = 3963.1905919

b = 3949.90276423189



Code: gravus2.py


'''

Earth's Gravity in US Units

EWS 05/26/2026

'''


from math import *


# title screen

print("Earth's Gravity")

print("Given Latitude and Elevation")

print("U.S./Imperial Units")

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


# angles must be converted to radians


print("Latitude in DMS:")

l1=eval(input("Whole Degrees? "))

l2=eval(input("Whole Minutes? "))

l3=eval(input("Seconds? "))

langle=l1+l2/60+l3/3600

# convert to radians

langle*=pi/180

# elevation

elev=eval(input("Elevation in feet? "))

# calculate radius 

a=3963.1905919

b=3949.90276423189

erad=(a**4+b**4*(tan(langle))**2)

erad/=(a**2+b**2*(tan(langle))**2)

erad=sqrt(erad)

# calculation

g=32.17192-0.08530*cos(2*langle)

g*=(erad/(erad+elev/5280))**2

print("Earth's radius: {0:.5f} mi".format(erad))

print("Estimated Gravity: {0:.5f} ft/s**2".format(g))



Examples (Results are rounded to five decimal places)



Latitude (φ)

Height (h ft)

Earth’s Radius (mi)

g_h (ft/s^2)

34°03’00”

500

3959.04875

32.13857

64°11’27”

1650

3952.43868

32.21979

10°57’00”

395

3962.71501

32.09156





Source



Grainger Engineering Office of Marketing and Communications. (answer written by Rebecca H.) (2016, November 21). “How gravitational force varies at different locations on Earth.” Illinois. https://van.physics.illinois.edu/ask/listing/64061. Retrieved March 10, 2026.

Planetcalc. “Earth Radius by Latitude (WGS 84)” Timur. 2021. https://planetcalc.com/7721/ Retrieved March 22, 2026.



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, August 22, 2026

Python (TI-84 Evo) and HP 32S: Shannon-Wiener Diversity Index

Python (TI-84 Evo) and HP 32S: Shannon-Wiener Diversity Index



Introduction



The Shannon-Wiener Diversity Index measures a level of how diverse a group of populations are by the following formula:


H = -Σ( p_i * ln(p_i), i = 1 to n) = Σ( -p_i * ln(p_i), i = 1 to n)


where p_i = (population of segment i) ÷ (total population)


As stated by M. Robert F. (see Sources), there are three levels of diversity:


Low Diversity: H < 1.5

Medium Diversity: 1.5 ≤ H ≤ 2.5

High Diversity: H > 2.5




Python: diverse.py

This script was done with a TI-84 Evo. The script uses only the math module and should be able to use on any calculator with Python.


# Math Calculations

from math import *


print("Shannon-Wiener Diversity\nIndex")

print("Enter a list of populations.")

lpop=eval(input("list: "))

# sum

s=sum(lpop)

# proportions

lpro=[i/s for i in lpop]

# -p log p

llog=[-i*log(i) for i in lpro]

# diversity index

h=sum(llog)


# results

print("diversity index:\n{0:.5f}".format(h))

if h>2.5:

  print("high diversity")

elif h<1.5:

  print("low diversity")

else:

  print("medium diversity")


HP 32S Program: Shannon Wiener Diversity Index


This was programmed on an original HP 32S, and the code should be same for the later HP 32SII and Swiss Micros DM32.


Instructions:

If need be, clear the variables

Enter the population size in the variables A, B, C, D etc… up to 25.

Enter the number of populations, XEQ A


Four labels are used:

LBL A: program start, initialization

LBL Z: determine total population (pop = A + B + C + D….)

LBL Y: determine proportion of each population (A = A/pop, B = B/pop, C = C/pop, …)

LBL X: calculate the Shannon-Weiner Diversity Index: -Σ(p_i * ln(p_i) from i=1 to n)



Code:

A01 LBL A

A02 ENTER

A03 ENTER

A04 ENTER

A05 CL x

A06 STO Z

A07 R↓

A08 STO i


Z01 LBL Z

Z02 RCL(i)

Z03 STO+ Z

Z04 R↓

Z05 DSE i

Z06 GTO Z

Z07 STO i

Z08 RCL Z


Y01 LBL Y

Y02 STO÷ (i)

Y03 DSE i

Y04 GTO Y

Y05 R↓

Y06 STO i

Y07 CL x

Y08 STO Z


X01 LBL X

X02 RCL (i)

X03 ENTER

X04 LN

X05 ×

X06 +/-

X07 STO+ Z

X08 DSE i

X09 GTO X

X10 RCL Z

X11 RTN


Size:

LBL A: 12.0 bytes

LBL Z: 12.0 bytes

LBL Y: 12.0 bytes

LBL X: 16.5 bytes

Total: 52.5 bytes


This does not count the 9.5 bytes needed for each variable used (Z, i, A, B, C, etc.). This program takes up to 25 populations (A through Y).



Examples


Example 1:


4 populations (n = 4).


A = 40

B = 30

C = 70

D = 20


Index: 1.2820 (low diversity index)


Example 2:


9 populations (n = 9).


A = 41

B = 36

C = 40

D = 97

E = 64

F = 37

G = 16

H = 18

I = 36


Index: 2.06303 (medium diversity index)



Sources



M. Robert F. The Math Behind Biology Lightning Source4 LLC. LaVergne, TN. 2026. pp. 6-8


Nolan, K.A. and J.E. Callahan. 2006. Beachcomber biology: The Shannon-Weiner Species Diversity Index. Pages 334-338, in Tested Studies for Laboratory Teaching, Volume 27 (M.A. O’Donnell, Editor). Proceedings of the 27th Workshop/Conference of the Association for Biology Laboratory Education (ABLE), 383 pages. 2006. ISBN 1-890444-09-X. Article: https://www.ableweb.org/biologylabs/wp-content/uploads/volumes/vol-27/22_Nolan.pdf. Retrieved May 6, 2026.





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, August 8, 2026

Python: Combination Functions (Micropython)

Python: Combination Functions (Micropython)


This is a set of combination functions. Programmed with a Casio fx-CG 100 but should work on any calculator with Python.


The script is freeware.


Functions included:


 fact(n): Factorial of the non-negative integer n. Some math modules include a factorial function, like Numworks. This function will be used in all the functions on this script.


ncr(n,r): Combination


npr(n,r): Permutation


nhr(n,r): Combination, repetitions are allowed


catalan(n): nth Catalan Number


narayana(n,k): Narayana Number (n, k are positive integers)


binpdf(n,k,p): Binomial Probability:

n: trials

k: number of successes

p: probability of success


bndcdf(n,k,p): Cumulative Binomial Probability – Lower Tail

n: trials

k: number of successes (from 0 to k)

p: probability of success



Script: combo.py

'''

combinatorics 4/12/2026

Edward Shore


round to nearest integer:

int(f+.5)

'''


from math import *


# factorial positive integers

def fact(n):

  f,i=1,1

  while i<=n:

    f*=i

    i+=1

  return int(f+.5)


# a lot of functions will use fact


# combination

def ncr(n,r):

  f=fact(n)/(fact(r)*fact(n-r))

  return int(f+.5)


# permutation

def npr(n,r):

  f=fact(n)/fact(n-r)

  return int(f+.5)


# combination w/repetitions

def nhr(n,r):

  f=fact(n+r-1)/(fact(r)*fact(n-1))

  return int(f+.5)


# catalan numbers

def catalan(n):

  f=fact(2*n)/(fact(n)**2*(n+1))

  return int(f+.5)


# narayana numbers

def narayana(n,k):

  f=1/n*ncr(n,k)*ncr(n,k-1)

  return int(f+.5)


# binomial probability

def binpdf(n,k,p):

  # p=prob

  f=ncr(n,k)*p**k*(1-p)**(n-k)

  return f


# bin lower tail

def bincdf(n,k,p):

  # 0 to k, p=prob

  s=0

  for i in range(k+1):

    s+=binpdf(n,i,p)

  return 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.


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)...