Quickly getting a slice of digits from a float

三世轮回 提交于 2021-02-10 13:31:19

问题


Suppose I could look at a float as if it was some sort of a dict, in which the the keys range from -infinity to infinity, and the values are the digits in these places. That is, f[i] will return the integer which is closest to (f % 10**(i+1) - f % 10**i) / 10**i.

For example, if f=1234.5678, f[-1] == 5 and f[2] == 2.

Furthermore: imagine the float would also support some weird form of image slicing (even though it is not a list, just like it is not a dict), so in our example f[-1:2] == 345.

I need this for practical reasons, and I need it to be done quickly. I guess I can write some clumsy stuff based on the expression I wrote in the first paragraph (which returns a float, with all of the problems of floats, which I should carefully convert to an integer).

So I wondered whether there's some simpler, or at least more elegant, quick solution (performance is an issue here), which does not involve libraries such as decimal.

It might worth mentioning that I am not looking after a solution which emulates the __getitem__ or the slice notation. A function def getslice(f, a, b) is perfectly fine.


回答1:


you could change it to string.

mystr = str(num)

then by having the position of '.' in mystr:

mystr[pos+index] 

is what you need, where index is your way of defining the position before and after the floating point.



来源:https://stackoverflow.com/questions/21908605/quickly-getting-a-slice-of-digits-from-a-float

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