'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.



Solution 1:[1]

You can use

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

Solution 2:[2]

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. It sets with how much precision numbers from array are printed. You can use the variable j as index.

If I may add a comment, what is the nature of you variable 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"). At each new run of the loop for i in np.arange(0,80): you will write the value. Otherwise write each value of K1 to an array and once the loop is finished print the whole array to a file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joseph Bani
Solution 2 Aldehyde