简体   繁体   English

在python中求解指数方程

[英]Solve equations for exponent in python

This code solves for the exponent in x^n + y^n - z^n = 0 by brute force.此代码通过蛮力求解 x^n + y^n - z^n = 0 中的指数。 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

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 .然后从scipy.optimize导入minimize_scalar并求解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).您还可以访问每个输出值(如xniter等)。 Besides, the computation really is a no-timer.此外,计算确实是无计时器的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM