Is there a quick way to find the maximum value (float) from a function and the corresponding arguments x, y that are both integers between 0 and 100 (inclusive)? Do I need to use the assert function or something like that to get the range of all possible inputs?
def fun_A(x,y):
import math
if x == y:
return 0
first = math.cos((y%75)*(math.pi/180))
second = math.sin((x%30)*(math.pi/180))
return (first + second) / (abs(x - y))
For small problems like this it is probably fast enough to evaluate every possible combination and choose the maximum. The numpy library makes this easy to write and pretty fast as well:
import numpy as np
def fun_A(x, y):
first = np.cos((y%75)*(np.pi/180))
second = np.sin((x%30)*(np.pi/180))
return np.where(x == y, 0, (first + second) / (abs(x - y)))
x, y = np.mgrid[0:101, 0:101]
f = fun_A(x, y)
maxindex = np.argmax(f)
print('Max =', f.flat[maxindex], ' at x =', x.flat[maxindex], 'y =', y.flat[maxindex])
Output:
Max = 1.4591796850315724 at x = 89 y = 88
Things to note:
I've just replaced calls to math with calls to np.
x and y are matrices which allow us to evaluate every possible combination the two values in one function call.
I would do this for the tan function :
from math import tan
y = 0
x = 0
for x_iteration in range(0, 101):
if tan(x_iteration) > y :
x = x_iteration
y = tan(x_iteration)
x = int(x)
y = int(y)
It's fairly straightforward to write a program to solve this:
max_result = None
max_x = 0
max_y = 0
for x in range(0, 101):
for y in range(0, 101):
result = fun_A(x, y)
if max_result is None or result > max_result:
max_result = result
max_x = x
max_y = y
print(f"x={max_x} and y={max_y} produced the maximum result of {max_result}")
Related
I have system of differential equations. I must do the Jacobian Matrix, and get it to the method, to find the stability step by using 2/max(abs(eigenvalue)) = hst
I am trying to make it like this
x, y, z = symbols("x y z")
J = Function('J')(x, y, z)
#Setting the Jacobian matrix elements
f1_swpx_angle_ball_step1 = 'arctg(x)'
print(f1_swpx_angle_ball_step1)
f1_swpy_angle_ball_step1 = 'y/(x*x+1)'
print(f1_swpx_angle_ball_step1)
f1_swpz_angle_ball_step1 = '0'
print(f1_swpx_angle_ball_step1)
f2_swpx_angle_ball_step1 = '-3*arctg(x)'
print(f2_swpx_angle_ball_step1)
f2_swpy_angle_ball_step1 = '-3*(x+3.27)/(y*y+1)'
print(f2_swpy_angle_ball_step1)
f2_swpz_angle_ball_step1 = '0'
print(f2_swpy_angle_ball_step1)
f3_swpx_angle_ball_step1 = "1/(x*x+1)"
print(f2_swpy_angle_ball_step1)
f3_swpy_angle_ball_step1 = "0"
print(f2_swpy_angle_ball_step1)
f3_swpz_angle_ball_step1 = "(0)"
print(f3_swpz_angle_ball_step1)
#Setting the Jacobian matrix elements
F3_switchball_angle_step1 = Matrix([[f1_swpx_angle_ball_step1, f1_swpy_angle_ball_step1, f1_swpz_angle_ball_step1],
[f2_swpx_angle_ball_step1, f2_swpy_angle_ball_step1, f2_swpz_angle_ball_step1],
[f3_swpx_angle_ball_step1, f3_swpy_angle_ball_step1, f3_swpz_angle_ball_step1]])
getting some values from print
jaceiglist = list(JacobianF_falling_angle_ball_step1.eigenvals())
print(jaceiglist)
[-0.5*sqrt(1.0*arctg(5)**2 - 0.399230769230769*arctg(5) + 0.910556360946746) + 0.5*arctg(5) - 0.477115384615385, 0.5*sqrt(1.0*arctg(5)**2 - 0.399230769230769*arctg(5) + 0.910556360946746) + 0.5*arctg(5) - 0.477115384615385, 0]
#trying to make a method, that get differentiable variables, and substituting the values, will calculate the current Jacobi matrix and the stability step
def hstabilitygetting_angle_ball_step1(MatrixForYacobian, values):
print("Matrix Shape ",MatrixForYacobian.shape)
JacobianF_falling_angle_ball_step1 = Matrix(
MatrixForYacobian.subs([(x, values[0]), (y, values[1]), (z, values[2])]))
print("Jacobian Matrix shape after substitute", JacobianF_falling_angle_ball_step1.shape)
jaceiglist = list(JacobianF_falling_angle_ball_step1.eigenvals())
print("Eigenvalues",jaceiglist)
return 2 / (reduce(lambda x, y: abs(x) if abs(x) > abs(y) else abs(y), jaceiglist))
I can't make this list values to float
JacobianF_falling_angle_ball_step1 = sympy.Matrix(F3_switchball_angle_step1.subs([(x,5),(y,5),(z,0)]))
jaceiglist = list(JacobianF_falling_angle_ball_step1.eigenvals()) print(jaceiglist) eq=sympy.S(str(jaceiglist[0])) eq.subs(sympy.Function('arctg'), sympy.atan ) eq.subs(sympy.Function('sqrt'), math.sqrt)
print((eq).evalf(),'Value')
eq = ((eq).evalf())
getting
-0.5*(1.0*arctg(5)**2 - 0.399230769230769*arctg(5) + 0.910556360946746)**0.5 + 0.5*arctg(5) - 0.477115384615385
This is an expression, and I need to make it float, get max(abs(values list), to have stability step.
print(float((eq).evalf()),'Value') TypeError: Cannot convert expression to float
When expressions involving arctg were sympified, unknown functions of that name were created. You should replace them with atan:
>>> eq=S('-3*arctg(x)')
>>> eq.subs(Function('arctg'), atan)
-3*atan(x)
Maybe like this:
>>> jaceiglist = Tuple(*JacobianF_falling_angle_ball_step1.eigenvals())
... .subs(Function('arctg'), atan)
Note: This is for homework so please don't post full code responses, just help on what I'm misusing would be appreciated
I'm trying to plot a piecewise defined function where when 0 < x <= 10 it will be a constant (KQ/10) and for x > 10 it will be KQ/x for 10 < x < 50. Currently my result comes back as a single value instead of my expected result of an array with a constant value up until x > 10 and then varying values until x = 50
My current code
import matplotlib.pyplot as plt
import scipy
x = np.linspace(0, 50, 1)
R = 10
r = np.linspace(10, 50, 1)
k = 1/(4*np.pi*constants.epsilon_0)
Q = 1
def inside(x):
return k*Q/R
def outer(x):
return k*Q/x
result = np.piecewise(
x,
[x <= R, x > R ],
[lambda x: inside(x), lambda x: outer(x)]
)
result
#plt.plot(x,result)
#plt.axis([0, 50,0, 500000])
#plt.xlabel('x')
#plt.ylabel('y')```
x = np.linspace(0, 50, 1)
isnt how linspace works... this only creates one data point ...
x = np.linspace(0, 50, 10000) ... would create 10k datapoints
perhaps you wanted np.arange(0,50,1) ?
I can calculate the root of a function using Newtons Method by subtracting the old x-value from the new one and checking for the convergence criterion. Is there a way of doing it when given a closed interval, e.g
Given a function and the interval [a,b] = [0.1, 3.0], the convergence criterion will be calculated by checking if [3.0 - 0.1] < 0.000001, i.e [b-a] < 0.000001.
The code I provided is calculating the convergence criterion using the x-values. I'm trying to figure out if there is a way I can use the interval instead of the x-values.
from math import *
x = 1.0 #initial value
for j in range(1, 101):
xnew = (x**2 + cos(x)**2 -4*x)/(2*(x - cos(x)*sin(x) -2))
if abs(xnew - x) < 0.000001:
break
x = xnew
print('Root = %0.6f ' % xnew)
print('Number of iterations = %d' % j)
It sounds like you are wanting to guarantee that the root is found within a given interval (which is not something the Newton-Raphson can guarantee). You could use bisection for this. If you know the function changes sign in a given interval (and is continuous in the same) then something like the following works:
>>> from sympy.abc import x
>>> from sympy import nsolve
>>> ivl = 0,3
>>> expr = (x**2 + cos(x)**2 -4*x)
>>> nsolve(expr, x, ivl)
0.250324492526265
But it also looks like you might have some variables mixed up in what you are trying with the NR method. The xnew you are calculating looks very much like f(x)/f'(x) which is dx in xnew = x - dx. So if you write:
for j in range(1, 101):
dx = (x**2 + cos(x)**2 -4*x)/(2*(x - cos(x)*sin(x) -2))
if abs(dx) < 0.000001:
break
x = x - dx
print('Root = %0.6f ' % x)
print('Number of iterations = %d' % j)
you will get
Root = 0.250324
Number of iterations = 4
I am currently trying to code a programm in python which result in drawing the mandelbrot set. The shape of the fractal looks ok but the outline isn't precise at all. I am trying to figuring if the problem comes from my maths or my code
I tried to raise the max number of iterations (which I called i) to see if the calculation was just too low but it didn't change much.
import numpy as np
from PIL import Image
taille = 1000
nb_points = 500
centre_x = taille/2
centre_y = taille/2
fractale = np.zeros((taille, taille, 3), dtype = np.uint8)
for x in range(-nb_points,nb_points):
x = float(x)
x = x/250
for y in range(-nb_points,nb_points):
y = float(y)
y = y/250
X = float(0)
Y = float(0)
i = 0
module_carre = 0
while module_carre < 4 and i <20 :
X = float(X**2 - Y**2 + x)
Y = float(2*X*Y + y)
i += 1
module_carre = float(X*X + Y*Y)
if module_carre < 4:
i=0
couleur = liste_couleur[i]
fractale[centre_x + x*250,centre_y + y*250] = couleur
imgpil = Image.fromarray(fractale, 'RGB')
imgpil.save("resultat.jpg")
I am French that's why you might not understand everything. I didn't paste all the lines about defining differents shades of blue etc...
I don't understand why my outline is this bad. I believe that it comes from my maths but i don't see any errors.
It's my first time posting on stack overflow and i don't understand evey tools yet. I didn't manage to add the image of the output
Sorry for my English and I hope you'll be able to help me fix my code
The main problem is here:
X = float(X**2 - Y**2 + x)
Y = float(2*X*Y + y)
In the calculation for Y, you want to use the old value of X, but it's already been updated and is no longer available. You could instead do:
new_X = float(X**2 - Y**2 + x)
Y = float(2*X*Y + y)
X = new_X
Or you could update them in parallel:
X, Y = float(X**2 - Y**2 + x), float(2*X*Y + y)
Also, you don't need the calls to float, so all you really need is:
X, Y = X**2 - Y**2 + x, 2*X*Y + y
By the way, Python does have a built-in complex number class, so you could initialize z and Z as z = complex(x, y) and Z = complex(0.0, 0.0).
Then your loop body would have:
Z = Z**2 + z
I also suggest increasing the maximum number of iterations. Limiting it to 20 will give very low resolution. I usually use at least 1000, at least for points near the boundary, when generating high-res images.
from random import randint as r
x = r(1, 100)
y = r(1, 10)
def rannum(x,y):
if (x==y):
m = 2*y
else:
z = x * y
print z
rannum(x,y)
I have value of x and y which are randomly generated and I have a function which has two condition. How could I construct loop to meet my x==y condition? How could I know home many times I ran the loop to meet this condition. I am fairly new to programming and got stuck to this point. Please suggest/recommend me the way to achieve the result. I have made the range of smaller so that there could be high probability of selecting same number.Thankyou
I don't know why you are doing it, but below is what I understand from your question.
from random import randint as r
def rannum(x,y):
if (x==y):
m = 2*y
print m
else:
z = x * y
print z
count=0
while True:
count=count+1
x = r(1, 100)
y = r(1, 10)
if (x==y):
print "x is equal to y after count=",count
rannum(x,y)
break