简体   繁体   English

错误:需要浮点参数,而不是 numpy.ndarray

[英]Error: float argument required, not numpy.ndarray

I am getting an error when running the following program.运行以下程序时出现错误。 I am trying to write the output to a file in a disk.我正在尝试将输出写入磁盘中的文件。

import time
start_time = time.clock()

import numpy as np
theta=6
sigma=np.linspace(0,10,80)
Re=np.linspace(5,100,80)

import os
completeName = os.path.abspath("New Volume (F:)/new innings 2/Sigma at 100 @80 .txt")
file = open("Sigma at 100 @80.txt", "w")


for i in np.arange(0,80):
    mu=np.sqrt(Re[i]*sigma)
    A=(mu-1)*np.exp(mu)+(mu+1)*np.exp(-mu)
    B=2*mu*(theta-1)
    C=(A/B)

   D1=np.exp(mu)/2*(mu+sigma)
   D2=np.exp(-mu)/2*(mu-sigma)
   D3=mu**2
   D4=np.exp(-sigma)
   D5=sigma
   D6=mu**2-sigma**2
   D7=D3*D4
   D8=D5*D6
   H=D7/D8
   D9=(1/sigma)
   D=D1-D2+H-D9
   K1=C-D
   K11=np.array(K1)
   print K11
   file.write("%g\n" % K11)

file.close()
print time.clock() - start_time, "seconds"

I am getting the error我收到错误

TypeError: float argument required, not numpy.ndarray 

corresponding to对应于

file.write("%g\n" % K11)

Kindly make some suggestions.请提出一些建议。 Thanks in advance.提前致谢。

您可以使用

file.write("%g"*len(K11)+"\n" % tuple(K11))

Try to replace尝试更换

file.write("%g\n" % K11)

by经过

for j,value in enumerate(K11):
    file.write(f"{value:10.5f}\n")

About the specifier 10.5f , change 5 to any desired value.关于说明符10.5f ,将 5 更改为任何所需的值。 It sets with how much precision numbers from array are printed.它设置打印数组中数字的精度。 You can use the variable j as index.您可以使用变量j作为索引。

If I may add a comment, what is the nature of you variable K1 ?如果我可以添加评论,您变量K1的性质是什么? It looks like it is already a float.看起来它已经是一个浮点数了。 In that case no need to use array, just print K1 in the file as a float file.write(f"{K1:10.5f}\n") .在这种情况下,无需使用数组,只需将文件中的K1打印为 float file.write(f"{K1:10.5f}\n") At each new run of the loop for i in np.arange(0,80): you will write the value.for i in np.arange(0,80):您将写入该值。 Otherwise write each value of K1 to an array and once the loop is finished print the whole array to a file.否则将K1的每个值写入一个数组,一旦循环完成,将整个数组打印到一个文件中。

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

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