在人工智能数学基础一书中,下面是一题Python求函数极限的例子:
【例2.6】使用Python编程求 lim( x → 1) (x^2 - 1 / x - 1)
—————————————————————————————————————————
import sympy
from sympy import oo #注意无究符号表示形式为两个小定字母o
import numpy as np
x = sympy.Symbol('x') #注意Symbol首字母大写
f = (x ** 2 - 1) / (x-1) # 定义极限表达式
lim = sympy.limit(f,x,1)
print(lim)
2
—————————————————————————————————————————
import sympy
from sympy import oo
import numpy as npx = sympy.Symbol('x')f = (x**2-1) / (x-1)print(sympy.limit(f,x,1))
这Python带的库真的是强大。
下面我们如果用C++来模拟,注意:下面代码只是最初构思,运算符重载还要修改。
#include "X:\Work\Share\CCode\CPlatform\Math\_math_out.h"using namespace lf;int main()
{ga.initialize();_Variable x;_function f;//f(x) = (x ^ 2 - 1) / (x - 1); f(x) = (x ^ 2 - 1 ) / (x - 1);_cout << f.limit() << _t("\n");return 0;
}
运行结果,这里没有添加任何库:
_Variable定义和_function定义:
class _Variable : public _Object
{
private:_DList<_Variable> _multiple;
public:_Variable();~_Variable();_Variable operator-(const int& n) const;_Variable operator+(const int& n) const;_Variable operator/(const int& n) const;_Variable operator/(const _Variable& other) const;// 重载加法运算符_Variable operator+(const _Variable& other) const;_Variable operator*(const _Variable& other) const;_Variable operator^(const _Variable& other) const;_Variable operator^(const size_t& nPower) const;
private:};class _function : public _Object
{
public:_function(const _Variable& v);_function();_function& operator()(const _Variable& other);_Variable limit()const;
};//--------------------------------------------------------_Variable::_Variable()
{}_Variable::~_Variable()
{}_Variable _Variable::operator-(const int& n) const
{_cout << _t("_Variable _Variable::operator-\n");return _Variable();
}_Variable _Variable::operator+(const int& n) const
{_cout << _t("_Variable _Variable::operator+\n");return _Variable();
}_Variable _Variable::operator/(const int& n) const
{_cout << _t("Variable _Variable::operator/\n");return _Variable();
}_Variable _Variable::operator/(const _Variable& other) const
{_cout << _t("_Variable::operator/\n");return _Variable();
}_Variable _Variable::operator+(const _Variable& other) const
{_cout << _t("_Variable _Variable::operator+\n");return _Variable();
}_Variable _Variable::operator*(const _Variable& other) const
{_cout << _t("_Variable _Variable::operator*\n");return _Variable();
}_Variable _Variable::operator^(const _Variable& other) const
{_cout << _t("_Variable::operator^\n");return _Variable();
}_Variable _Variable::operator^(const size_t& nPower) const
{_cout << _t("_Variable::operator^\n");return _Variable();
}_function::_function(const _Variable& v)
{
}_function::_function()
{
}_function& _function::operator()(const _Variable& other)
{_cout << _t("_function::operator()\n");return *this;
}_Variable _function::limit() const
{_cout << _t("这里求函数极限!\n");return _Variable();
}