old code
from math import copysign
error=float(input("enter the error limit"))
d=float(input("enter the value of d"))
x0=float(input("enter the value of x0"))
x1=float(input("enter the value of x1"))
i=0.0
def f(x):
y=x**2-d
return y
if(copysign(1,f(x0))==copysign(1,f(x1))):
print("wrong initial points")
print("valies krdena print")
exit()
print("iteration i x0 x1 x2 f(x0) f(x1) f(x2)")
while abs((x1-x0)/x1)>error:
x2=(x0-x1)/2
i+=1
if(copysign(1,f(x0))==copysign(1,f(x2))):
x0=x2
print("x0 <-- x2 ",f'{i:7.5}'," ",f'{x0:.5f}'," ",f'{x1:.5f}'," ",f'{x2:.5f}'," ",f'{f(x0):.5f}'," ",f'{f(x1):.5f}'," ",f'{f(x2):.5f}')
else:
x1=x2
print("x1 <-- x2 ",f'{i:7.5}'," ",f'{x0:.5f}'," ",f'{x1:.5f}'," ",f'{x2:.5f}'," ",f'{f(x0):.5f}'," ",f'{f(x1):.5f}'," ",f'{f(x2):.5f}')
print("root is ",x2)
print("iteration",i)
print(f(x2))
import pandas as pd
from math import copysign
error = float(input("Enter the error limit: "))
d = float(input("Enter the value of d: "))
x0 = float(input("Enter the value of x0: "))
x1 = float(input("Enter the value of x1: "))
i = 0.0
def f(x):
y = x ** 2 - d
return y
if copysign(1, f(x0)) == copysign(1, f(x1)):
print("Wrong initial points. Please provide different initial points.")
exit()
data = []
while abs((x1 - x0) / x1) > error:
x2 = (x0 - x1) / 2
i += 1
if copysign(1, f(x0)) == copysign(1, f(x2)):
x0 = x2
data.append([i, x0, x1, x2, f(x0), f(x1), f(x2)])
else:
x1 = x2
data.append([i, x0, x1, x2, f(x0), f(x1), f(x2)])
columns = ['iteration', 'x0', 'x1', 'x2', 'f(x0)', 'f(x1)', 'f(x2)']
df = pd.DataFrame(data, columns=columns)
print(df)
print("Root is", x2)
print("Iteration", i)
print("f(x2) =", f(x2))
For "error limit": This is the tolerance you want for the error in your root approximation. It indicates how close the root approximation should be to the actual root. For example, you might input 0.001 if you want the approximation to be accurate to three decimal places.
For "value of d": This is the number for which you want to find the square root. For example, if you want to find the square root of 25, you would input 25.
For "value of x0" and "value of x1": These are the initial guesses for the root. They should ideally be chosen such that the function changes sign between them. For example, if you're trying to find the square root of 25, you might choose x0 = 0 and x1 = 6, as the function f(x) = x^2 - 25 changes sign between these values.
So, to run the code, you should provide the appropriate inputs according to the problem you're trying to solve.