简体   繁体   English

绘制从文件读取的数据时,浮点数无效,并且出现浮点除法错误

[英]Invalid literal for float when plotting data read from a file, and a floating point division error

I've got a script that takes the output of a separate C++ executable and creates a scatter plot/bifurcation diagram of the resulting data. 我有一个脚本,该脚本接受一个单独的C ++可执行文件的输出,并创建所得数据的散点图/分叉图。 The application context is to look at angle values versus the driving force by iterating through multiple values of a driving force to get the resulting angle and stroboscopically sampling the results, as a problem regarding a nonlinearly damped driven pendulum from a course on computational physics 应用上下文是通过迭代驱动力的多个值来获取角度并通过频闪法对结果进行采样,从而观察角度值与驱动力的关系,这是一个关于非线性阻尼从动摆的问题,来自计算物理学课程

import os
import sys
import numpy as np
import matplotlib.pyplot as plt

gbl      = 1.0
kappa    = 0.5
T_D      = 9.424778
ic_ang   = 0.1
ic_avel  = 0.0
t_final  = 200
Nstep    = 7500
method   = "runge_kutta"

ic_ang   = 0.1
Fmin     = 0.8
Fmax     = 1.6
F_D      = float(Fmin)

tstep    = T_D/(t_final/Nstep)
Nrep     = 3 * tstep
select   =[]
step     = 0.01
Nite     = (Fmax-Fmin)/step
rng      = int(Nite-1)

for i in range(rng):
    pfile= open('param.dat','w')
    pfile.write('%f %f %f %f\n' %(gbl,kappa,F_D,T_D))
    pfile.write('%f %f %f\n'%(ic_ang,ic_avel,t_final))
    pfile.write('%d %s\n'%(Nstep,method))
    pfile.close()

os.system('./a.out > bif.log')

with open("data.out",'r') as datafile:
    data=datafile.readlines()

select=data[-Nrep:Nstep:int(tstep)]

for j in select:
    plt.plot(F_D, j, "o", color='b', markersize=0.3)
    print(F_D,j)
F_D += step
plt.xlabel(r'$F_D$')
plt.ylabel(r'$\theta_{repeat}$')
#plt.xticks([])
plt.yticks([])
plt.show()

However, when I try to run the script I get 但是,当我尝试运行脚本时,我得到了

Traceback (most recent call last):
File "bif.py", line 45, in <module>
plt.plot(F_D, j, "o", color='b',markersize=0.3)

File"/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/pyt hon/matplotlib/pyplot.py", line 2987, in plot
ret = ax.plot(*args, **kwargs)

File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/matplotlib/axes.py", line 4138, in plot
self.add_line(line)

File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/matplotlib/axes.py", line 1497, in add_line
self._update_line_limits(line)

File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/matplotlib/axes.py", line 1508, in 
_update_line_limits
path = line.get_path()

File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/matplotlib/lines.py", line 743, in get_path
self.recache()

File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/matplotlib/lines.py", line 429, in recache
y = np.asarray(yconv, np.float_)

File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/numpy/core/numeric.py", line 460, in asarray
return array(a, dtype, copy=False, order=order)

ValueError: invalid literal for float(): 0 0.1 0 0.004995834722

Modifying some of the values to try and debug the script raises a separate exception 修改某些值以尝试调试脚本会引发单独的异常

Traceback (most recent call last):
File "bif.py", line 24, in <module>
tstep    = T_D/(t_final/Nstep)
ZeroDivisionError: float division by zero

I am extremely new to Python so neither one of these exceptions makes much sense to me. 我对Python非常陌生,因此这些异常中的任何一个对我来说都没有多大意义。 However, as Nstep , t_final , and T_D all have finite values, there is no reason (that I can see anyhow) for a dividing by zero error. 但是,由于Nstept_finalT_D都具有有限值,因此没有理由(无论如何我都可以看到)除以零误差。

I see possible errors for the ValueError as well, as the output in the 1st and 3rd columns (time and angular velocity) aren't float values as they should be. 我也看到了ValueError可能错误,因为第一列和第三列中的输出(时间和角速度)不是应该的浮点值。 I don't, however, know why these values aren't being converted to a float as they should be. 但是,我不知道为什么未将这些值转换为浮点数。

Any help would be very much appreciated. 任何帮助将不胜感激。

EDIT:THIS ISSUE HAS BEEN SOLVED 编辑:此问题已解决

I think you're asking two questions here, and as I can see the last one about division by zero is the easier one. 我认为您在这里问两个问题,正如我所看到的关于零除的最后一个比较容易。 Namely, the expression t_final/Nstep , as it stands now in your code, is an integer division expression , and the result is 0 . 即,现在在您的代码中表示的表达式t_final/Nstep一个整数除法表达式 ,结果为0 Thus the line 因此线

tstep    = T_D/(t_final/Nstep)

divides by zero. 除以零。

The second question is why matplotlib complains about the data. 第二个问题是为什么matplotlib抱怨数据。 To really diagnose this problem we need to look at the content of the data file read by your program. 要真正诊断此问题,我们需要查看程序读取的数据文件的内容。 However, I think the problem stems from your attempt to pass text (Python string) to a function expecting numeric data type. 但是,我认为问题出在您试图将文本(Python字符串)传递给期望数值数据类型的函数。 When you readlines() the input file, I don't think you're doing any conversion. 当您在readlines()输入文件中时,我认为您没有进行任何转换。 As a result, a slice of text string is passed to plt.plot and matplotlib struggled to construct a numeric data type from this representation. 结果,一片文本字符串被传递到plt.plotmatplotlib努力从此表示形式构造数字数据类型。 It would be much better if you read the data, do the proper conversion according to the file format and the logic of your analysis. 如果您读取数据,根据文件格式和分析逻辑进行正确的转换,那就更好了。 You may want to look into numpy.loadtxt if it's the case that you're dealing with a text data file. 如果正在处理文本数据文件,则可能需要查看numpy.loadtxt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM