Don "Quixote" Eisele's page of Campaign Cartographer stuff

Square Root function for CC2 - Heron's Method

I was needing a square root function to create some shapes based on the area of other shapes, and I couldn't find the square root function in the manual, help files, or old postings on the cc2-macros list.

I did find a post from 2002 that stated there wasn't a square root function, so I've written an approximation function that gets accurate enough results for my purposes, and thought I would share.

This is known as Heron's Method.

Basically I've set it up so that it will continue to get a closer approximation until there are two approximations in a row that are within varSQRTround of each other. I decided to base varSQRTround on my initial value, so that I'd get a reasonable square root if my square was small or large.

The .mac file for direct download

Usage:
GV varSQRT 30
SQRT
GV MyAnswer varSQRT


// Commented source.  don't just cut/paste this, download the .mac file directly
MACRO SQRT

// square root of zero is zero.  We don't want to deal with irrational numbers
IFZ varSQRT MacroDone
IFN varSQRT MacroDone

// Start out with a guess of half of the square
GV varSQRTb (varSQRT/2)

// precision is .00001 of the square
GV varSQRTround (.00001*varSQRT)

:MacroLoop
GV varSQRTa varSQRTb

// Main workhorse:  create a new guess based on the old guess and 
// dividing the old guess into the square.  Each iteration will
// get closer to the real value
GV varSQRTb (.5*(varSQRTa+(varSQRT/varSQRTa)))

// This is all stuff to compare the latest to values and see if we
// are close enough to stop
GV varSQRTdiff (varSQRTa-varSQRTb)
IFN varSQRTdiff MacroNeg
GV varTol (varSQRTdiff-varSQRTround)
IFN varTol MacroFound
GOTO MacroLoop
:MacroNeg
GV varTol (varSQRTdiff+varSQRTround)
IFP varTol MacroFound
GOTO MacroLoop

// return the value
:MacroFound
GV varSQRT varSQRTb
:MacroDone
ENDM