Welcome, guest | Sign In | My Account | Store | Cart

I realised a lack of an nth root function within Python maths' modules, even though, you could fulfil the task by using the power function, and I wrote nth-Root program. However, I used Newton’s method Xn+1 = Xn - f(Xn)/f’(Xn) , n = 1,2,3... and worked out myself the formula to solve the equation X^(b) - a for nth-root(a) as follows: Xn+1 = 1/b((b-1)Xn + a/Xn^(b-1)). Though my program nth-Root uses a generator to generate each value approximation in the sequence from its predecessor, and it display the nth root value once two equal values are generated. Nowadays Scientifics’ calculators display 9 digits to the right of a decimal point and my program nth-Root displays a 16 figures precision to the right of a decimal point.

Python, 134 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#On the name of ALLAH and may the blessing and peace of Allah 
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 27/07/09
#version :2.6

"""
nth-Root program uses generators to compute values' approximations
of a sequence and displays the nth root of a number, once two equal
values are generated consecutively.
"""
from __future__ import generators
from decimal import *

def nthRoot(n,x):
    """ Returns the nth root of a number """

    seq_start = 1.0         #sequence starting value 
    counter = 0             #initialize the generator counter to zero 

    if x < 0:
        raise ValueError,\
            " Cannot compute a Square root on a negative number"
    elif n == 0:
        raise ValueError,\
            " Cannot compute 0 root of a number"
    
    while counter < 700:
            
        yield seq_start     #return nthRoot(x)
        
        #compute the next sequence term (Xn+1)    
        seq_start = 1/float(n) * ((n-1)*float(seq_start )+ x/(float(seq_start)**(n-1)))
        
        
        counter += 1
                       
while True:
    
    try:
        #get the nth root number from user
        nth = int(raw_input("Please Enter a nth root (n) : "))
        #get a number from user
        number =  int(raw_input("Please Enter a number (x): "))
        
    except ValueError:
        print "This value is not an integer"

    else:
        break

    print
    
seq_list = []       # start with an empty list

for i in nthRoot(nth,number):
    seq_list.append(i)  # append the list 
    
    if seq_list.count(i)>1: 
        seq_list.remove(i)
        
if number == 0:
    # Display nth root(0)
    print "The %s root of %s is : %s" \
            % (nth,number,int(Decimal(repr(i)).normalize()))          
else:
    #Display the nth root (x)
    print "The (%s)root of %s is : %s" \
            % (nth,number,Decimal(repr(i)).normalize())

  

###############################################################################
   

#>>> 
#>>> The (22552222)root of 22 is : 1.000000137061557
#>>> 
#>>> The (5) root of 0 is : 0
#>>> The (2)root of 25 is : 5
######################################################################################

#Version : Python 3.2

#from decimal import *

#def nthRoot(n,x):
#    """ Returns the nth root of a number """
    
#    seq_start = 1.0         #sequence starting value 
#    counter = 0             #initialize counter to zero
#    if x < 0:
#        raise ValueError(" Cannot compute a Square root on a negative number")
#    elif n == 0:
#        raise ValueError(" Cannot compute 0 root of a number")            
#    while counter < 700:
#            
#        yield seq_start     #return nthRoot(x)
#        
#        #compute the next sequence term (n+1)
#        seq_start =  1/float(n) * ((n-1)*float(seq_start )+ x/(float(seq_start)**(n-1)))
#            
#        counter += 1
#                       
#while True: 
#    try:
#        #get the nth root number from the user
#        nth = int(input("Please enter a nth root (n) : "))
#        #get the number from the user
#        number =  int(input("Please enter a number (x): "))
#        
#    except ValueError:
#        print("<This value is not an integer. ")
#
#    else:
#        break
#    
#    print()
#
#seq_list = []       #start with an empty list
#    
#for i in nthRoot(nth,number):
#    seq_list.append(i) #append the list
#
#    if seq_list.count(i)>1:
#        seq_list.remove(i)
#if number == 0:
#    #Display nth root(0)
#    print("The %s root of %s is : %s" \
#            % (nth,number,int(Decimal(repr(i)).normalize())))
#else:
#    #Display nth root(x)
#    print("The %s root of %s is : %s" \
#            % (nth,number,Decimal(repr(i)).normalize()))  

14 comments

Fouad Teniou (author) 14 years, 9 months ago  # | flag

Though you could always increment the precision figures by using the getcontext ().prec function from the decimal module which is set to 28 digits

Gabriel Genellina 14 years, 9 months ago  # | flag

Not to dismiss your work, it may be useful as an example of an iterative procedure, but number**(1./nth) is infinitely faster and works with a wider range of inputs. Try number=1e20, nth=20; answer should be 10.

(Also, I wonder why you use "int" to input data, then repeatedly and unnecesarily convert to "float" along all the computations, and finally use "Decimal" to print the result?)

Fouad Teniou (author) 14 years, 9 months ago  # | flag

Thank you for your effort, however, you should know that the yield function is special and does have its sides’ effects, and when generating the items in the sequence, the value n must be converted into a float before the next item in the sequence is generated. And I had already mention in my program’s introduction above that Python maths modules power’s function which uses the ^( 1/nth ) does fulfil the task, but I stress the need for an nth root function, which I produced myself and could be added to Python maths module, The fact that Python maths’ modules do have a separate function to perform the square roots, and yet it could be also computed using the power function ^( ½). And I used ( int ) to convert the roots of the zero value, because even the value is extremely small, it is still computed by the yield function within the generator, while avoiding the ZeroDivisionError. Though Newton’s method was genius, yet I had to work out the hidden formula with a pen and on a paper while having a cup of coffee and thinking…

Alia Khouri 14 years, 9 months ago  # | flag

You have a wonderful insight into the hidden formulae of computer languages. Have you ever tried perl 6 by the way?

Fouad Teniou (author) 14 years, 9 months ago  # | flag

I was thinking by the way, and it was a hidden mathematics’ formula I worked out not computers’.

However, Python is a secret language used by -the others- who want to run the world, I mean the planet since they are inside out different than humans and do rely on a supernatural hidden –thing - just not to scare you a creature inside a human body, but not a snake, while Perl is still a perfect language invented for the purpose.

And I am still different even they call me 7.

Fouad Teniou (author) 14 years, 9 months ago  # | flag
Gabriel Genellina 14 years, 8 months ago  # | flag

Wow, I'll propose you for the Fields Medal on the IMU congress next year!

py> number = 1E20 py> nth = 20 py> print number**(1./nth) 10.0

Try the same values in your program and see what happens.

Fouad Teniou (author) 14 years, 8 months ago  # | flag

Please find the link to the IMU congress nomiation guidelines below.

http://www.mathunion.org/general/prizes/nomination-guidelines/

However, as I already had mention, I wrote my program for a purpose of using directly nth numbers not the 1./nth, because it is better and more simple.

Though life is too complicated and solving mathematics' problems make it easier.

Alia Khouri 14 years, 8 months ago  # | flag

I suppose you are free to to spend your life/time solving solved problems in a more complicated way, but why you insist on sharing these as 'recipes' is beyond me.

Fouad Teniou (author) 14 years, 8 months ago  # | flag

I noticed a question for solving this problem in Calculus 7th University Edition, but it did not have an answer, thus, I solved it my self as you can see in my introduction. However, Calculus is for students in higher education (mathematics branch), and it is never too late for yourself to catch-up.

Alia Khouri 14 years, 8 months ago  # | flag

In python, it is preferable not to have many different ways to do things, so if the language can already do what your program already does and more quickly and succinctly, then your effort doesn't really add much value to others.

If you get this single point, then you will begin to get python.

Fouad Teniou (author) 14 years, 8 months ago  # | flag

I used Newton’s method and worked out my self this formula,

Xn+1 = 1/b((b-1)Xn + a/Xn^(b-1)).

And hello again, this is mathematics and it does not have anything to do with python.

I hope that you are not trying to put other python’s programmers off, as you are trying with myself, because it wouldn’t work, and you could always find something better to do with your time.

Alia Khouri 14 years, 8 months ago  # | flag

I'm certainly not trying to put you off, but you are posting python code in a python recipes section, so you shouldn't feel offended or get defensive if someone gives you constructive criticism about your recipe and poses the simple question: is it useful to other python programmers?

Fouad Teniou (author) 14 years, 8 months ago  # | flag

I hope that you do check other people recipes in this site and see for yourself the way that others do criticise python programs, and do make points by suggesting other solutions within the program context and not by trying to tell people that their programs are good, bad, needed or not by python’s programmers or by trying to deviate people from knowing the importance of a such program as this is your case in this occasion ( My Mathematics nth root formula) .

I triggered you in the past that some do have Evils Mark birth’s sign and cannot hide it because they could be checked and it is plain for others to see once they know the hidden location, yet they still do make comments in this site and other sites .

However, whether they do have Muslims’ names or not, they still be checked for this purpose at a point or another.