Formula to Calculate the Cube Root of a Number

If you have questions about any aspect of QBasic programming, or would like to help fellow programmers solve their problems, check out this board!

Moderators: Pete, Mods

Post Reply
User avatar
michealey
Coder
Posts: 11
Joined: Sun Dec 03, 2006 8:31 pm
Location: Florida
Contact:

Formula to Calculate the Cube Root of a Number

Post by michealey » Wed Jan 17, 2007 1:41 pm

Hi Guys,

I was wondering if anyone knew of a simple way to calculate the "cube root" of a number...

(I need it for applying Keplers Third Law in a space game I am building.)


Any help very kindly appreciated.


Kind Regards,

Mic

User avatar
Patz QuickBASIC Creations
Veteran
Posts: 399
Joined: Wed Mar 02, 2005 9:01 pm
Location: Nashville, Tennessee
Contact:

Post by Patz QuickBASIC Creations » Wed Jan 17, 2007 4:29 pm

I don't know if this works in QBASIC, but another way to do it is to raise it to the power of 1/3. Example:

Code: Select all

num = num ^ (1/3)
I don't have a terminal I can test this out on, but it is a mathmatically sound way to do it. If it doesn't work, it's QB's problem.

If that does work, then this is a function you could use to find the n-th root of a number...

Code: Select all

FUNCTION Root (Raise, N!)
Root = Raise ^ (1/N!)
END FUNCTION

User avatar
michealey
Coder
Posts: 11
Joined: Sun Dec 03, 2006 8:31 pm
Location: Florida
Contact:

Formula for Roots

Post by michealey » Wed Jan 17, 2007 7:31 pm

That works great!!!!!!!! Thanks so much for that. So simple too! Very very excellent. Much thanks.


Very Sincerely,

Mic

User avatar
Quibbler
Coder
Posts: 16
Joined: Tue Jan 24, 2006 7:29 am
Location: Trinidad and Tobago

Post by Quibbler » Mon Jan 22, 2007 7:39 am

Ok so maybe you only need the real root for your calcs. Here's something for your amusement it calculates all the roots - so just like a square root has 2 solutions a cube root has 3 solutions. I have set it to do the cube root of 8. So the answers are 2 and -1?sqr(3)i.


I have edited this as line 8 comes out wrong when the code is pasted as code ( that's the line IF ri<0>=0 THEN) ARRRRRRGGG!!! it's done it again.
What this line should say is IF RI less than zero AND RR greater than or equal to zero then...

Code: Select all

DEFDBL A-I, P-Z
REM***** finds the nth root of rr + ri ******
n = 3: rr = 8: ri = 0
REM******************************************
pi = 3.1415926536#
IF rr = 0 THEN g = pi / 2# ELSE g = ATN(ABS(ri) / ABS(rr))
IF ri >= 0 AND rr < 0 THEN g = pi - g
IF ri <0>= 0 THEN g = 2# * pi - g
IF ri < 0 AND rr < 0 THEN g = g + pi
r = SQR(ri * ri + rr * rr)
f = EXP(LOG(r) / n)
PRINT ""
h = (2# * pi)
PRINT "        Real         Imaginary"
WHILE m < n
real = f * COS(g / n): imag = f * SIN(g / n)
PRINT USING "  +##.########## +##.##########&"; real; imag; "i"
g = g + h
m = m + 1
WEND

Post Reply