Python Forum
Solving an equation by brute force within a range - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Solving an equation by brute force within a range (/thread-36674.html)



Solving an equation by brute force within a range - alexfrol86 - Mar-17-2022

Hello! I try to solve the equation sqrt(x**2 + y**2) by brute force within the range [0, 10]. Please help me make this code work

def eq(x, y):
    i = sqrt(x**2 + y**2)
    return sqrt(x**2 + y**2)
eps = 0.001
step = eps / 2
i = (0, 10, step)
for x in range (-10, 10, step):
  for y in range (-10, 10, step):
    while eq(x, y) == i:
      print(f"x = {x}, y = {y}")



RE: Solving an equation by brute force within a range - kabeer_m - Mar-17-2022

There seems to be quite a few problems with your code.
1. You aren't using indentations correctly
2. you are using sqrt for applying square root, but that is a function from the math library. I recommend using (x**0.5), it is
the same as square root.
3. The range function of python does not allow float values, as you are trying to apply.
4. For calling a function inside a print statement, use the format < print(function_name(x,y)) >

Below is a solution for the printing the values from 0,10 :

def eq(x, y):
    i = (x**2 + y**2)**0.5
    return i

for i in range (0, 10):
    print(eq(i,i))
for the values in the range you specified, I recommend using numpy, as it has a range function that supports float values :
import numpy as np

def eq(x, y):
    i = (x**2 + y**2)**0.5
    return i

eps = 0.001
delta = eps / 2
r = np.arange(0,10,delta)

for i in r:
    print(eq(i,i)) 
please take a look at some tutorials, if you are very confused.
Hopefully this helps


RE: Solving an equation by brute force within a range - alexfrol86 - Mar-17-2022

Thank you so much!


RE: Solving an equation by brute force within a range - Gribouillis - Aug-09-2022

(Aug-09-2022, 09:20 AM)Estherbarnes Wrote: (x**0.5) isn't the same as square root, it gives another result, doesn't it? Huh
When x is a nonnegative float, it should give the same result, but it turns out that for negative floats, Python returns the principal complex square root for x**0.5 while sqrt(x) raises a math domain error. So these are not exactly the same functions.
>>> (-1)**0.5
(6.123233995736766e-17+1j)
>>> from math import sqrt
>>> sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error
For a general object, the expression x ** 0.5 returns x.__pow__(0.5), so the result depends on how the class of x defines the __pow__() method, which can be very arbitrary.