How to take the ln of a function in python?

匿名 (未验证) 提交于 2019-12-03 01:36:02

问题:

I used polyfit to find a fitline of a data set, but now I need to find the natural log of that fitline function and plot it. Here's what I have so far:

#Fit line for PD deg = 10 zn = np.polyfit(l_bins, l_hits, deg) l_pn = np.poly1d(zn) pylab.plot(l_bins, l_pn(l_bins), '-g') ln_list = [] for all in l_bins:     ln_list.append(np.log(l_pn(all))) pylab.plot(l_bins, ln_list, '-b') 

Is there a better or more correct way to do this?

回答1:

Edit
I would suggest using numpy.log as Roger Fan demonstrated below. Since you are already using numpy arrays, this will certainly outperform using map or a list comprehension.


Original answer
If you have a list of z-values, you can use map to perform some function to each value, in this case log (which is ln).

>>> x = range(1,10) >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9]  >>> from math import log >>> map(log, x) [0.0, 0.6931471805599453, 1.0986122886681098, 1.3862943611198906, 1.6094379124341003, 1.791759469228055, 1.9459101490553132, 2.0794415416798357, 2.1972245773362196] 

You could use any function, so you may use numpy.log if you prefer.



回答2:

It seems that you just want the values for the originally provided bins. In that case, this is simpler and will be much faster.

ln_list = np.log(l_pn(l_bins)) 

Keep in mind that numpy functions will generally apply themselves element-wise to an array if it makes sense to do so.



回答3:

log(x) is 10 based, while ln(x) is natural logarithm based.

Ok, talk is cheap, show the code:

import math x = 8 print math.log(x, math.e) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!