Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Pure Python Square root without using Math.sqrt()
# This program is just an example of how you can calculate the square root of a number in pure Python without the math.sqrt() function. # If you find this insightful thats good because this doesn't have any specific purpose. # The math module was imported only for checking purposes. import math # Method to calculate the root of the given number in form of a integer. # That why the name: *INTEGRAL* Root. def integral_root(number, power = 2): for i in range(int(number)+1): if i**power == number: return i elif i**power > number: return i-1 def root(number, power = 2, precision = 13): num = str(integral_root(number, power)) + "." # Making a floating number in form of a string. # Checking if the integral root of the given number is the actual root. # Example: integral root of 25 is 5, and it is the actual answer as well. if(float(num)**power == number): return float(num) for i in range(min(precision + 1, 16)): added = False # Boolean to store if the next digit has been added. # The calculation of the root takes place digit by digit. for j in range(1, 10): n = float(num + str(j)) # Getting the floating point number from the string. # If the number to the required power is equal to the actual number then the answer has been found. if n**power == number: return n elif n**power > number: num += str((j-1)) added = True # the number was added so set 'added' to true. break # Adding a 9 to the string form of the number if no other digit was added. if not added: num += "9" # I don't know how to explain it, but this is very much required for proper calculation. return float(num) # Returning the answer. ''' MAIN PROGRAM START This program is able to calculate pretty accurately. This program has been tested with upto power of 500, and the results were pretty accurate! ''' number = float(input("Enter the number: ")) # Getting the number. powe = int(input("Enter the power: ")) # Getting the power of the root. print(root(number, power = powe, precision = 15)) # Calculating the root and printing. print(math.pow(number, 1/powe)) # Statement for checking purpose. # MAIN PROGRAM END # PROGRAM BY 'JAMES COLLINS'
run
|
edit
|
history
|
help
0
try123
MBTI
linked_lists_2
Юра и заселение
Range List for Python
pyCustomEnum
pythonic way (V2)
НОД по Евклиду на ПИТОНЕ
pythonfin
H.W5