This code solves for the exponent in x^n y^n - z^n = 0 by brute force. Would there be a faster and cleaner way to do this?
import math
for n in range(-10, 100000000):
n /= 1000000.0
x = 16**(n) 20**(n)-25**(n) #formula to solve must equal zero
if round(x,2) == 0:
print('exponent is: ',n, ', error is: ',x); break
CodePudding user response:
You can define your function that should be minimized (in your case equal to zero):
def f(n):
return 16**(n) 20**(n) - 25**(n)
and then import minimize_scalar
from scipy.optimize
and solve your equation for n
.
from scipy.optimize import minimize_scalar
minimize_scalar(f)
-------------------------------
fun: 0.0
nfev: 55
nit: 35
success: True
x: -518.3839114719358 # x is your n that solves your equation
-------------------------------
Check:
f(-518.3839114719358) # -> 0.0
Checkout the documentation for more. There are additional options you can give the function (like bounds). You also can access each output value (like x
, niter
, and so on). Besides, the computation really is a no-timer.