我正在寻找一种有效的方法来用python确定两个浮点数的最大公约数。该例程应具有以下布局
gcd(a, b, rtol=1e-05, atol=1e-08)
"""
Returns the greatest common divisor of a and b
Parameters
----------
a,b : float
two floats for gcd
rtol, atol : float, optional
relative and absolute tolerance
Returns
-------
gcd : float
Greatest common divisor such that for x in [a,b]:
np.mod(x,gcd) < rtol*x + atol
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
"""
Run Code Online (Sandbox Code Playgroud)
示例:有理数和无理数的gcd
本gcd(1., np.pi, rtol=0, atol=1e-5)
应返回(大约)1e-5
,如
In [1]: np.mod(np.pi,1e-5)
Out[1]: 2.6535897928590063e-06
In [2]: np.mod(1.,1e-5)
Out[2]: 9.9999999999181978e-06
Run Code Online (Sandbox Code Playgroud)
我宁愿使用库实现而不是自己编写它。该fractions.gcd功能似乎不适合我在这里,因为我不希望与分工作,它(显然)不具有耐受性的参数。
问题:
matplotlib.path中函数 contains_point 中的 radius 参数定义不一致。此函数检查指定点是否位于闭合路径的内部或外部。半径参数用于使路径变小/变大(取决于半径的符号)。这样,可以将靠近路径的点纳入考虑/不考虑。问题是,半径的符号取决于路径的方向(顺时针或逆时针)。(在我看来)不一致是存在的,因为在检查点是在路径内部还是外部时,路径的方向被忽略。从严格的数学意义上来说:路径上剩下的所有东西都包括在内。
简而言之:
如果路径逆时针方向,则正半径会考虑更多点。如果路径是顺时针方向,则正半径会考虑较少的点。
例子:
在以下示例中,检查了 3 种情况 - 每种情况都针对顺时针和逆时针路径:
代码:
import matplotlib.path as path
import numpy as np
verts=np.array([[-11.5, 16. ],[-11.5, -16. ],[ 11.5, -16. ],[ 11.5, 16. ],[-11.5, 16. ]])
ccwPath=path.Path(verts, closed=True)
cwPath=path.Path(verts[::-1,:], closed=True)
testPoint=[12,0]
print('contains: ','|\t', '[12,0], radius=3','|\t', '[12,0], radius=-3','|\t', '[0,0]|')
print('counterclockwise: ','|\t'
,'{0:>16s}'.format(str(ccwPath.contains_point(testPoint,radius=3) )),'|\t'
,'{0:>17s}'.format(str(ccwPath.contains_point(testPoint,radius=-3) )),'|\t'
,ccwPath.contains_point([0,0],radius=0) ,'|\t'
,'=> radius increases tolerance \t'
)
print('clockwise: ','|\t'
,'{0:>16s}'.format(str(cwPath.contains_point(testPoint,radius=3) )),'|\t'
,'{0:>17s}'.format(str(cwPath.contains_point(testPoint,radius=-3) )),'|\t'
,cwPath.contains_point([0,0],radius=0) ,'|\t'
,'=> radius decreases tolerance …
Run Code Online (Sandbox Code Playgroud) 我正在寻找一种将字典写入 Pandas DataFrame 行的单行解决方案。另一种方式非常直观地使用类似的表达式df.loc[2, :].to_dict(dct)
.
插图
我正在寻找一个镜头表达式来替换for key in dct.keys()
以下代码中的-loop:
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.arange(12).reshape(3,4), columns=list('abcd'))
>>> dct = {'a': 77, 'c':-1}
>>>
>>> df
a b c d
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
>>> dct
{'a': 77, 'c': -1}
>>>
>>> for key in dct.keys():
... df.loc[1, key] = dct[key]
...
>>>
>>> df
a b …
Run Code Online (Sandbox Code Playgroud) python ×3
contains ×1
dataframe ×1
dictionary ×1
matplotlib ×1
numpy ×1
pandas ×1
path ×1
point ×1