from array import array
scores = array('d')
scores.append(90)
scores.append(91)
print(scores)
print(scores[1])
How do we remove the decimal point from the result of an array?
scores = array('d') initializes an array of doubles (as denoted by 'd') rather than integers. If you want to hold an array of values without decimals construct an array this way you could write array('i').
You might also want to take a look at other data types that may fit your needs.
If you just want to print the values without the decimal you can cast them into integers when printing as such: print(int(scores[1]))
You can string format to 0 decimal points print("{0:.0f}".format(scores[1])).
So the value of the element '90' you stored while appending in the array is of data type float
You can eliminate decimal by converting the value to float while printing as follows
print(int(scores[1]))
Also you can use round() for eg round(arr[i],1)
Related
I'm interested in taking a single integer and converting it to a numpy array of 1's and 0's equal to the number's binary representation. I'd like to fix the length of the array (pad with zeros as needed) while I'm at it. How can this been done?
Something along these lines:
>>> func(19,bits=7)
np.array([0,0,1,0,0,1,1])
Use Python's bin() for binary conversion
def func(x, bits):
return np.array([int(i) for i in bin(x)[2:].zfill(bits)])
Explanation
bin(x)[2:] slices the binary-specific prefix from the string representation of the binary data. Subsequently, zfill() appends leading zeros. However, it only does so when the number of bits is sufficient to represent the integer input x as a binary vector. Otherwise, it is neglected. Finally, a list comprehension [int(i) for i in ...] is used as the input to the NumPy array constructor.
The advantage of the implementation is that it does not require to pre-define the range of the integer input or checking for the validity of the number of bits.
When calculating the following 2**1000 for example you get the whole value
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
But if you do the same for a float i.e 1.2**1000 it gives
1.5179100891722457e+79
Is there a built-in way to get the whole value of such a calculation (Not in scientific notation)?
The reason for the behavior you're seeing is that the first expression results in an integer since both of its operands are integers, while the second expression is a floating point number because one of the operands is a float. To get the result you want, you can cast the result of the second expression to an int:
>>> int(1.2**1000)
15179100891722457049849556131606991918673074938672571271083893226004713928916992L
You should be able to use format()
a = 1.2**1000
print(format(a, 'f'))
Gives the output 15179100891722457049849556131606991918673074938672571271083893226004713928916992.000000
Try casting to an integer.
int(1.2 ** 1000)
If you want to get decimals though you'll need to do some additional work depending on your goal
You can use this to print it
print("{:.3E}".format(1234567890987654321))
This will output:
1.235E+18
You can also have decimal values. It will format it similarly.
print("{0:.3E}".format(1234567890987654321.98765432))
1.235E+18
If you want to get the full number printed, then you can do the following:
y = 1234567890987654321.98765432
print(f"{y:.22}")
It will output:
1234567890987654400.0
I am trying to extract my analysis result in .txt file. The results show as below :
-3.298409999999999854e+04 -3.298409999999999854e+04
-3.297840000000000146e+04 -3.297840000000000146e+04
Code:
anodeIdx = [10,20,30]
stressAnodeXX = [x for i,x in enumerate(stress_xx[0].Y) if i in anodeIdx]
stressAnodeYY = [x for i,x in enumerate(stress_yy[0].Y) if i in anodeIdx]
np.savetxt('Stress_strain_Anode.txt',np.c_[stressAnodeXX,stressAnodeYY])
I expected the result to be -32984.1 but the actual output is -3.2984099999e+4
To save the number in a specific way, you can use optional parameter fmt of np.savetxt(). Documentation
In your case:
np.savetxt('Stress_strain_Anode.txt',np.c_[stressAnodeXX,stressAnodeYY], fmt='%.1f')
f is specifier wihch saves the number as decimal floating point.
.1 Represents how many decimal numbers should be after the decimal point.
I think the problem here is not the numbers not being rounded, but not being appropiately formatted.
You could use the fmt keyword argument of numpy.savetxt to solve this. (numpy documentation):
np.savetxt('Stress_strain_Anode.txt', np.c_[stressAnodeXX,stressAnodeYY], fmt='%.1f')
Where '%.1f' is a format string which formats numbers with one decimal digit.
Your result is actually -32984.1. Float representation in binary code is not ideal so you see it in a bit confusing way. If you want, you can just round your result (but it is not needed):
np.round(your_result_number, decimals=1)
which will return:
-32984.1
More about your result:
-3.2984099999e+4 has two confusing parts:
099999 in the end of number
e+4 in the end of output
e+4 is a scientific notation of your number. It means: "multiply it to 10^4=10000. If you will do it, you will get 3.29841 * 10000 = 32984.1
099999... in the end of the number appears because computer tries to represent decimal float number in binary code, which leads to small "errors". So your result is actually -32984.1.
I'm currently trying to take integer arrays that actually represent other data types and convert them into the correct datatype.
So for example, if I had the integer array [1196773188, 542327116], I discover that this integer array represents a string from some other function, convert it, and realize it represents the string "DOUGLAS". The first number translates to the hexadecimal number 0x47554F44 and the second number represents the hexadecimal number 0x2053414C. Using a hex to string converter, these correspond to the strings 'GOUD' and 'SAL' respectively, spelling DOUGLAS in a little endian manner. The way the letters are backwards in individual elements of the array likely stem from the bytes being stored in a litte endian manner, although I might be mistaken on that.
These integer arrays could represent a number of datatypes, including strings, booleans, and floats.
I need to use Python 2.7, so I unfortunately can't use the bytes function.
Is there a simple way to convert an integer array to its corresponding datatype?
It seems that the struct module is the best way to go when converting between different types like this:
import struct
bufferstr = ""
dougarray = [1196773188, 542327116]
for num in dougarray:
bufferstr += struct.pack("i", num)
print bufferstr # Result is 'DOUGLAS'
From this point on we can easily convert 'DOUGLAS' to any datatype we want using struct.unpack():
print struct.unpack("f", bufferstr[0:4]) # Result is (54607.265625)
We can only unpack a certain number of bytes at a time however. Thank you all for the suggestions!
I have an numpy array of floats in Python.
When I print the array, the first value is:
[7.14519700e+04, ....
If, however, I print out just the first value on it's own, the print out reads:
71451.9699799
Obviously these numbers should be identical, so I just wondered, is the array just showing me a rounded version of the element? The second number here has 12 significant figures, and the first only has 9.
I guess I just wonder why these numbers are different?
It's just in the printing, not in the storage. The only confusion might occur because the first example uses numpy's print precision settings, the second example general python's print settings.
You can adjust the numpy precision and print by
numpy.set_printoptions(precision=20)
print myarray`
(adjust precision to your needs), or select the number of significant figures in standard python formatted print:
print ('%.20f' % myarray[0])
The internal representation of the number is always the same.
The types in a numpy array are well defined. You can get how they are stored by inspecting the numpy.dtype property of an array.
For example:
import numpy
a = numpy.zeros(10)
print a.dtype
will show float64, that is a 64-bit floating point number.
You can specify the type of the array explicitly using either the commonly accepted dtype argument, or the dtype type object (that is, the thing that makes the dtype).
a = numpy.zeros(10, dtype='complex32') # a 32-bit floating point
b = numpy.longdouble(a) # create a long-double array from a
Regarding the printing, this is just a formatting issue. You can twiddle how numpy prints an array using numpy.set_printoptions:
>>> a = numpy.random.randn(3) # for interest, randn annoyingly doesn't support the dtype arg
>>> print a
[ 0.12584756 0.73540009 -0.17108244 -0.96818512]
>>> numpy.set_printoptions(precision=3)
>>> print a
[ 0.126 0.735 -0.171 -0.968]