3

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.

user3738922
  • 57
  • 1
  • 4
  • It kind of says right there: %g expects one number, not an entire array. Either loop through it writing each one, or look up Numpy's special fileIO operations – Ben Jun 20 '14 at 16:21
  • 1
    What don't you understand? The error message tells you exactly the problem; you're passing an `array`, which can't be formatted with `'%g'`. – jonrsharpe Jun 20 '14 at 16:22
  • 2
    I asked here simply because I don't know how to write the entire array to a file. Any suggestion? – user3738922 Jun 20 '14 at 16:27
  • `file.write(' '.join(str(a) for a in K11))` – Korem Jun 20 '14 at 16:29
  • Thank you but it writes in indistinguishable form. Can the matrices be arranged in a better way? – user3738922 Jun 20 '14 at 16:34
  • 1
    Check here: http://stackoverflow.com/questions/2891790/pretty-printing-of-numpy-array – Korem Jun 20 '14 at 16:51
  • Does this answer your question? [How to pretty-print a numpy.array without scientific notation and with given precision?](https://stackoverflow.com/questions/2891790/how-to-pretty-print-a-numpy-array-without-scientific-notation-and-with-given-pre) – Tomerikoo Feb 09 '21 at 15:04

2 Answers2

0

You can use

file.write("%g"*len(K11)+"\n" % tuple(K11))
Joseph Bani
  • 644
  • 6
  • 16
0

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.

Aldehyde
  • 35
  • 8