Skip to content

Instantly share code, notes, and snippets.

@EDDYMENS
Last active January 23, 2024 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EDDYMENS/41ec93888ebabc2ea55e47c48aa686fc to your computer and use it in GitHub Desktop.
Save EDDYMENS/41ec93888ebabc2ea55e47c48aa686fc to your computer and use it in GitHub Desktop.
from decimal import Decimal
def find_square_root(number, decimal_places, current_result=None, current_decimal_place=1):
# Find the integer part of the square root
if current_result is None:
current_result = int(number / 2)
# Check if we have computed the required number of decimal places
if current_decimal_place-1 == decimal_places:
return current_result
# Try placing 0-9 in decimal positions to find the closest square
for possible_decimal in range(9, -1, -1):
candidate = current_result + Decimal(f'0.{str(possible_decimal).zfill(current_decimal_place)}')
squared_result = candidate * candidate
if squared_result <= number:
return find_square_root(number, decimal_places, candidate, current_decimal_place + 1)
# Example usage
decimal_places = 3
number = 2
result = find_square_root(number, decimal_places)
print(result) # 1.414
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment