
Python部落组织翻译, 禁止转载, 欢迎转发
nlib
这是一个纯Python的数值计算库, 不需要numpy
使用
>>> from nlib import *
线性代数例子
>>> A = Matrix([[1,2],[4,9]]) >>> print 1/A >>> print (A+2)*A >>> B = Matrix(2,2,lambda i,j: i+j**2)
拟合
>>> points = [(x0,y0,dy0), (x1,y1,dy1), (x2,y2,dy2), ...] >>> coefficients, chi2, fitting_function = fit_least_squares(points,POLYNOMIAL(2)) >>> for x,y,dy in points: >>> print x, y, '~', fitting_function(x)
求解器
>>> from math import sin >>> def f(x): return sin(x)-1+x >>> x0 = solve_newton(f, 0.0, ap=0.01, rp=0.01, ns=100) >>> print 'f(%s)=%s ~ 0' % (x0, f(x0))
优化
>>> def f(x): return (sin(x)-1+x)**2 >>> x0 = optimize_newton(f, 0.0, ap=0.01, rp=0.01, ns=100) >>> print 'f(%s)=%s ~ min f' % (x0, f(x0)) >>> print 'f'(%s)=%s ~ 0' % (x0, D(f)(x0))
统计
>>> x = [random.random() for k in range(100)] >>> print 'mu =', mean(x) >>> print 'sigma =', sd(x) >>> print 'E[x] =', E(lambda x:x, x) >>> print 'E[x^2] =', E(lambda x:x**2, x) >>> print 'E[x^3] =', E(lambda x:x**3, x) >>> y = [random.random() for k in range(100)] >>> print 'corr(x,y) = ', correlation(x,y) >>> print 'cov(x,y) = ', covariance(x,y)
财务计算
>>> google = YStock('GOOG') >>> current = google.current() >>> print current['price'] >>> print current['market_cap'] >>> for day in google.historical(): >>> print day['date'], day['adjusted_close'], day['log_return']
持久化存储
>>> d = PersistentDictionary(path='test.sqlite') >>> d['key'] = 'value' >>> print d['key'] >>> del d['key']
神经网络
>>> pat = [[[0,0], [0]], [[0,1], [1]], [[1,0], [1]], [[1,1], [0]]] >>> n = NeuralNetwork(2, 2, 1) >>> n.train(pat) >>> n.test(pat) [0, 0] -> [0.00...] [0, 1] -> [0.98...] [1, 0] -> [0.98...] [1, 1] -> [-0.00...]
绘图
>>> data = [(x0,y0), ...] >>> Canvas(title='my plot').plot(data, color='red').save('myplot.png')
项目地址
https://github.com/mdipierro/nlib

