Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中将浮点表示法转换为10科学表示法的幂?_Python_Matplotlib_Floating Point_Legend - Fatal编程技术网

如何在Python中将浮点表示法转换为10科学表示法的幂?

如何在Python中将浮点表示法转换为10科学表示法的幂?,python,matplotlib,floating-point,legend,Python,Matplotlib,Floating Point,Legend,在Python中,我将0.000001,0.00001,0.0001,…,1.0所给出的值存储在my_Array(np.Array)中。 对于这些值中的每一个,我需要在绘图中标记一条曲线,并将其存储在图例中,作为val=10e-6,而不是val=0.000001。 如果我使用(对于I的第四个值),则会自动存储第二个版本: 是否有一个函数将浮点表示法转换为10表示法的科学幂?您只需获得“%.2E%”和所需数字之间的整数 '%.2E' % Decimal('40800000000.000000000

Python
中,我将
0.000001,0.00001,0.0001,…,1.0
所给出的值存储在
my_Array
np.Array
)中。 对于这些值中的每一个,我需要在绘图中标记一条曲线,并将其存储在图例中,作为
val=10e-6
,而不是
val=0.000001
。 如果我使用(对于
I
的第四个值),则会自动存储第二个版本:


是否有一个函数将浮点表示法转换为10表示法的科学幂?

您只需获得“%.2E%”和所需数字之间的整数

'%.2E' % Decimal('40800000000.00000000000000')

# returns '4.08E+10'
如图所示

“%.2E%”四舍五入到第二个小数点。若要四舍五入到第一个整数,请使用“%.1E%”

-

要实现您的目标,只需:

x = 0.0001
y = '%.2E' % x

print (y)

# prints 1.00E-04

(根据jonrsharpe的提示编辑)

您可以结合使用
ScalarFormatter
FuncFormatter
将值格式化为mathtext。也就是说,它看起来不是0.01或1e-2


这与中的概念基本相同,只是不适用于轴,而适用于图例。

理论上,下面的功能应该可以正常工作,而无需调用专用函数。然而,版本3.11中有一些地方被破坏了,至少在ScalarFormatter中没有对功率限制进行检查

import matplotlib.ticker as mticker
f = mticker.ScalarFormatter(useMathText=True)
f.set_powerlimits((-3,3))
"${}$".format(f.format_data(0.0001))

这是内置于基本字符串格式中的,请尝试使用例如
格式(0.00001,.0e')
。是的,这是最好的解决方案转换为
十进制在这里是完全不必要的,该字符串格式适用于任何数字类型。请编辑您的答案,解释“2”四舍五入到第二个十进制?还有“你可以直接得到模数”是完全错误的,事实并非如此。这是与模数不同的
%
符号用法。我将尝试收集更多信息并编辑我的答案,然后你可以在你的答案中添加@jornsharpe提到的“format()”方法。
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

vals = [0.000001,0.00001,0.0001,0.01,1.0]

f = mticker.ScalarFormatter(useOffset=False, useMathText=True)
g = lambda x,pos : "${}$".format(f._formatSciNotation('%1.10e' % x))
fmt = mticker.FuncFormatter(g)

fig, ax = plt.subplots()
for i,val in enumerate(vals):
    ax.plot([0,1],[i,i], label="val = {}".format(fmt(val)))

ax.legend()    
plt.show()
import matplotlib.ticker as mticker
f = mticker.ScalarFormatter(useMathText=True)
f.set_powerlimits((-3,3))
"${}$".format(f.format_data(0.0001))