简体   繁体   English

如何在不使用 numpy.linspace() 的情况下在 Python 中创建线性 function

[英]How to create linear function in Python without using numpy.linspace()

So, i am trying to create a linear functions in python such has y = x without using numpy.linspace() .所以,我试图在 python 中创建一个线性函数,例如y = x而不使用numpy.linspace() In my understanding numpy.linspace() gives you an array which is discontinuous.在我的理解中 numpy.linspace() 给你一个不连续的数组。 But to fo但是为了佛

I am trying to find the intersection of y = x and a function unsolvable analytically ( such has the one in the picture ).我试图找到y = x和 function 无法解析的交集(图中有一个)。

Here is my code I don't know how to define x.这是我的代码,我不知道如何定义 x。 Is there a way too express y has a simple continuous function?有没有办法表达 y 有一个简单的连续 function?

import random as rd
import numpy as np

a = int(input('choose a :'))
eps = abs(float(input('choose epsilon :')))

b = 0
c = 10
x = ??????

y1 = x
y2 = a*(1 - np.exp(x))

z = abs(y2 - y1)
while z > eps :
    d = rd.uniform(b,c)
    c = d
    print(c)
print(y1 , y2 )

这是一张描述我正在尝试做的事情的图片

Since your functions are differentiable, you could use the Newton-Raphson method implemented by scipy.optimize :由于您的函数是可微的,您可以使用由scipy.optimize实现的Newton-Raphson 方法

>>> scipy.optimize.newton(lambda x: 1.5*(1-math.exp(-x))-x, 10)
0.8742174657987283

Computing the error is very straightforward:计算误差非常简单:

>>> def f(x): return 1.5*(1-math.exp(-x))
...
>>> x = scipy.optimize.newton(lambda x: f(x)-x, 10)
>>> error = f(x) - x
>>> x, error
(0.8742174657987283, -4.218847493575595e-15)

I've somewhat arbitrarily chosen x0=10 as the starting point.我有点武断地选择 x0=10 作为起点。 Some care needs to be take here to make sure the method doesn't converge to x=0, which in your example is also a root.这里需要注意确保该方法不会收敛到 x=0,在您的示例中它也是一个根。

I'm not a mathematician so perhaps you can explain me sth here, but I don't understand what exactly you mean by "unsolvable analytically".我不是数学家,所以也许你可以在这里解释一下,但我不明白你所说的“无法解析”到底是什么意思。

That's what sympy returns:这就是 sympy 返回的内容:

from sympy import *

x = symbols('x')
a = 1.5
y1 = x
y2 = a*(1 - exp(-x))
print(solve(y1-y2))

# [0.874217465798717]

“Not solvable analytically” means there is no closed-form solution. “无法解析解决”意味着没有封闭形式的解决方案。 In other words, you cant write down a single answer on paper like a number or equation and circle it and say ”thats my answer.”换句话说,你不能在纸上写下一个单一的答案,比如数字或方程式,然后把它圈起来,然后说“这就是我的答案”。 For some math problems it's impossible to do so.对于某些数学问题,这样做是不可能的。 Instead, for these kinds of problems, we can approximate the solution by running simulations and getting values or a graph of what the solution is.相反,对于这类问题,我们可以通过运行模拟并获取值或解决方案的图表来近似解决方案。

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

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