Jump to content

Nth root: Difference between revisions

Line 3,185:
rem - exercise the routine by finding successive roots of 144
var i = integer
var x = real
 
print "Finding the nth root of x"
print " x n root"
print "-----------nth------------"
for i = 1 to 8
print using "### #### ###.####"; 144; i; nthroot(144, i)
next i
 
end
</lang>
But if the six or seven digits supported by S-BASIC's single-precision REAL data type is insufficient, Newton's Method it must be, given that the built-in exp and natural log functions are only single-precision.
<lang basic>
rem - return the nth root of real.double value x to stated precision
function nthroot(n, x, precision = real.double) = real.double
var x0, x1 = real.double
x0 = x
x1 = x / n rem - initial guess
while abs(x1 - x0) > precision do
begin
x0 = x1
x1 = ((n-1.0) * x1 + x / x1 ^ (n-1.0)) / n
end
end = x1
 
rem -- exercise the routine
 
var xi = realinteger
print "Finding the nth root of 144 to 6 decimal places"
print " x n root"
print "------------------------"
for i = 1 to 8
print using "### #### ###.######"; 144; i; nthroot(i, 144.0, 1E-7)
next i
 
Line 3,197 ⟶ 3,222:
</lang>
{{out}}
From the second version of the program.
<pre>
Finding the nth root of x144 to 6 decimal places
x n root
-------------------------
144 1 144.0000000000
144 2 12.0000000000
144 3 5.2415241483
144 4 3.4641464102
144 5 2.7019701920
144 6 2.2894289428
144 7 2.0339033937
144 8 1.8612861210
</pre>
 
211

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.