I have the following
import math
import matplotlib.pyplot as plt
def nraphson(fn, dfn, x, tol, maxiter):
for i in range(maxiter):
xnew = x - fn(x)/dfn(x)
if abs(xnew - x) < tol: break
x = xnew
return xnew, i
y = lambda x: math.exp(x) - x**2
dy = lambda x: math.exp(x) - 2*x
x, n = nraphson(y, dy, j, 10**-5, 100)
guess = range(-10,6)
for j in guess:
print(nraphson(y, dy, j, 10**-5, 100))
my output is of the form
(-0.7034674225098828, 6)
(-0.7034674224990228, 6)
(-0.7034674224984084, 6)
(-0.7034674224983918, 6)
(-0.7034674224983917, 6)
(-0.703467422509882, 5)
(-0.7034674224984084, 5)
(-0.7034674224983917, 5)
(-0.7034674224984067, 4)
(-0.7034674224983924, 3)
(-0.7034674224983924, 4)
(-0.7034674224983917, 5)
(-0.7034674224983917, 6)
(-0.7034674224983917, 6)
(-0.7034674224984245, 8)
(-0.7034674224983917, 10)
I am attempting to isolate the second number from my output to form a list or array to us to plot a graph, how can I adjust my code as to give me a list or array like the following?
[6, 6, 6, 6, 6, 5, 5, 5, 4, 3, 4, 5, 6, 6, 8, 10]
CodePudding user response:
Replace the last two lines of your code with this:
L = [nraphson(y, dy, j, 10**-5, 100)[1] for j in guess]
print(L)
CodePudding user response:
If you just want to print the second values, in the for loop at the end:
for j in guess:
print(nraphson(y, dy, j, 10**-5, 100)[1])
In your code you were printing the result of nraphson(y, dy, j, 10**-5, 100)
, which is a tuple with two elements. To get the second element, just access it with [1]
.
If you don't want to print the values but want to create a list with those values, simply do something like this:
tuples = [nraphson(y, dy, j, 10**-5, 100) for j in guess]
second_nums = [t[1] for t in tuples]
CodePudding user response:
Try this:
...
guess = range(-10,6)
result = [nraphson(y, dy, j, 10**-5, 100)[1] for j in guess]
print(result)