**George Carter**

Home | Blog | All Tags | Now | Search

I’m an experiential learner. Whenever I’m given a principle, I’ll test it out, build a model…

And today I learnt about doing a binary search on the real number line to find or estimate fractional representations of decimals.

So I had to code it up.

And what system did I code it in? Well, one of the quickest preview languages I know… ZX Basic. (Yeah, I know).

So I fired up the ZX Spectrum emulator (JSSpeccy 3) and came up with this code:

10 GO SUB 30 20 STOP 30 REM ---Main--- 40 LET i=0: LET c=0 50 INPUT "Enter a decimal number: ";a 60 LET w= INT a 70 LET a=a-w 80 LET n1=0: LET d1=1: LET n2=1: LET d2=1 90 PRINT "You want ";w+a 100 REM ---Loop--- 110 LET i=i+1: LET c=c+1: IF i=10 THEN PRINT ".";: LET i=0 120 LET n=n1+n2 130 LET d=d1+d2 140 LET r=n/d 150 IF a=r THEN LET a$="Found": GO SUB 200: RETURN 160 IF (ABS (a-r) < 0.0001) OR (c=200) THEN LET a$="Estimated": GO SUB 200: RETURN 170 IF r < a THEN LET n1=n: LET d1=d: GO TO 100 180 REM n3/d3 must be bigger 190 LET n2=n: LET d2=d: GO TO 100 200 REM ---Show Result--- 210 PRINT 'w;" ";n;"/";d;" is "; w+n/d 220 PRINT 'a$;" in ";c;" steps." 230 RETURN

One thing that amuses me is my use of subroutines that I would never have done forty years ago when I was playing with Spectrums in my childhood. Gotta hit “return”, not ‘STOP’ in the middle of a program!

And what was really strange was that if I checked for “r=a” on line 150 it didn’t work due to rounding errors (you can test this yourself by comparing 1/2 vs. 0.5… one way round they’re equal, the other way round they’re not)… it’s due to the low precision of the floating point arithmetic on the Spectrum.

It gives up quite early (if it estimates to four decimal places or takes more than 200 steps). But given the slow computing speed of the Spectrum this was a necessary optimisation.

Anyhow, a fun little diversion.

And here’s what ChatGPT thought of it:

First off, kudos to you for diving into the fascinating world of ZX Basic programming! It’s always great to see enthusiasm for classic computing.

Tags: Amusement, Retro Computing, Tech

← 31 Days With A New Name | The Biggest Bug That Took 43 Years To Spot →

Happy to discuss anything you read here by email: blog@gamc.uk

## Leave a Reply