I am looking at this line of python code (which seems to run properly):
import numpy as np
yl = 300 + 63*np.exp(-x/35.)
What is the dot doing after the 35? what does it do? Is it a signal to python that 35 is a float and not an integer? I have not seen this before. Thanks!
This is easy to test, and you're right. The dot signals a float.
$ python
>>> 1.
1.0
>>> type(1.)
<type 'float'>
Float
Next time, try to explore this using Python
r= 34.
print type(r)
Output: <type 'float'>
It tells python to treat 3 as a float(). Its just a convenient way to make a number a float for division purposes then having to explicitly call float() on it.
For example:
my_float = 3.
typed_float = float(3)
my_float == typed_float
#=> True
type(my_float)
#=> <type 'float'>
In this case you need to typecast to a float to avoid the pitfalls of integer division.
Related
I would like to know how to write the equivalent representation to the following number in python:
-3.3999999521443642e+38
i did the following:
print(-3.3999999521443642*math.exp(38))
is it correct?
Python supports the scientific notation just as you stated in your question with e in the number:
>>> a=-3.3999999521443642e+38
>>> print(a)
-3.3999999521443642e+38
>>> type(a)
<class 'float'>
you can use as is
a = -3.3999999521443642e+38
print(a)
output
-3.3999999521443642e+38
Python understands this representation directly.
x = 44e10
print (x)
440000000000.0
It is just an elegant way to represent big numbers in a compact way.
I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.
Direct conversion fails:
>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45678'
I can convert it to a decimal by using:
>>> from decimal import *
>>> d = Decimal(s)
>>> print d
23.45678
I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.
But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.
How about this?
>>> s = '23.45678'
>>> int(float(s))
23
Or...
>>> int(Decimal(s))
23
Or...
>>> int(s.split('.')[0])
23
I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.
What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:
s = '234.67'
i = int(round(float(s)))
Otherwise, just do:
s = '234.67'
i = int(float(s))
>>> s = '23.45678'
>>> int(float(s))
23
>>> int(round(float(s)))
23
>>> s = '23.54678'
>>> int(float(s))
23
>>> int(round(float(s)))
24
You don't specify if you want rounding or not...
You could use:
s = '23.245678'
i = int(float(s))
"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.
You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).
round(float('23.45678'))
The expression int(float(s)) mentioned by others is the best if you want to truncate the value. If you want rounding, using int(round(float(s)) if the round algorithm matches what you want (see the round documentation), otherwise you should use Decimal and one if its rounding algorithms.
round(float("123.789"))
will give you an integer value, but a float type. With Python's duck typing, however, the actual type is usually not very relevant. This will also round the value, which you might not want. Replace 'round' with 'int' and you'll have it just truncated and an actual int. Like this:
int(float("123.789"))
But, again, actual 'type' is usually not that important.
I believe this is a useless bug that should be corrected in Python.
int('2') --> 2 That converts the string '2' into an the integer 2.
int(2.7) --> 2 Converts a float to an int.
int('2.7') SHOULD convert to 2. This is how Perl works, for example. Yes, this does two things at once. It converts the string and when it finds it is in a representation that is a float, it should convert to int.
Otherwise, why insist that float('2') should work? It is an integer string, because there is no decimal point. So it has to convert from string which is an integer, directly to float.
I don't know but perhaps someone can answer whether the python interpreter, if the required int(float(x)) is used, if it actually goes through the process of first converting to float and then converting to int. That would make this bug even more critical to correct.
I am new to python.And one of my requirement is to deal with long values.The problem is i didnt know how to assign a long value.This question might be very silly.But im just now starting to learn the language.I have seen a blog and i tried something like this :
# Long program in Python
x=1
y = long(x)
print(type(y))
But i am getting an error like this:
Traceback (most recent call last):
File "main.py", line 4, in <module>
y = long(x)
NameError: name 'long' is not defined
Can anyone please help me in acheiving this?
The long() function is no longer supported by Python 3 (no pun intended). It only has one built-in integral type, named int; but it behaves mostly like the old long type. So you just need to use int() built-in function in python-3.x.
Also for more information here are the complete list of changes on integer type in python-3.x:
PEP 0237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type.
PEP 0238: An expression like 1/2 returns a float. Use 1//2 to get the truncating behavior. (The latter syntax has existed for years, at least since Python 2.2.)
The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
The repr() of a long integer doesn’t include the trailing L anymore, so code that unconditionally strips that character will chop off the last digit instead. (Use str() instead.)
Octal literals are no longer of the form 0720; use 0o720 instead.
Forget about long vs. int or about lL suffixes. Python 2.7 will promote int to long if necessary. And all integers are "long" in Python 3 (the type is renamed to int).
Assume that integers have infinite precision in Python.
To assign and print large integer in Python, just assign and print it:
x = 2**100
print(x) # -> 1267650600228229401496703205376
It works on both Python 2 and 3. The result is the same.
Python 2.7.13 it works.
x=1
y = long(x)
type(y)
<type 'long'>
you no need to define a variable as 'long' in python. Python will take care of it by default
Eg :
>>> x = 1243254675876586798
>>> type(x)
<type 'long'>
Quote from diveintopython3:
Python 2 had separate types for int and long. The int datatype was
limited by sys.maxint, which varied by platform but was usually 2^32-1.
Python 3 has just one integer type, which behaves mostly like the old
long type from Python 2. See pep 237 for details.
Python interpreter allocates memory based on the data type of variable. Therefore, by assigning different data types to variables, you can store integers, strings and longs.
>>> a = "Hello"
>>> b = 123
>>> c = 123.0
>>> d = "a"
>>> type(a)
<type 'str'>
>>> type(c)
<type 'float'>
For specific to long type, you can append "l" or "L" in the value, caps "L" is recommended. Python
displays long integers with an uppercase L
>>> e = 1234L
>>> type(e)
<type 'long'>
>>> f=1234567891223341221
>>> f
1234567891223341221L
For variable "f", while displaying the value interpreter has appended "L" with value.
As mentioned by Kasra, in Python 2.x you can typecast variable type with long(), but this is no longer supported in Python 3. This is not required as Python interpreter usually takes care if value changes, until unless you want to do it explicitly
>>> b = 1234
>>> type(b)
<type 'int'>
>>> long(b)
1234L
So far, I would do int(float('3.5'))
Any other good way to do?
Note: 3.5 is a string.
I want to use the the built-in API that specify for this sort of problem.
You're on the right track, and the best solution is probably as mentioned:
>>> int(float("3.5"))
This truncates the float.
If you want a different type of rounding, you can use the math package:
>>> import math
>>> x = "3.5"
>>> math.floor(float(x)) # returns FP; still needs to be wrapped in int()
3.0
>>> math.ceil(float(x)) # same
4.0
>>> math.trunc(float(x)) # returns an int; essentially the same as int(float(x))
3
If on the other hand you wish to round the number to the nearest integer, you may use the floating-point built-in operation round before converting to an integer, e.g.
>>> int(round(float(x))) # 3.5 => 4
4
>>> int(round(3.4999))
3
The only code which could possibly be simpler and clearer than what you have is int('3.5'), which doesn't work. Therefore, what you have is the simplest, clearest working code.
All that you need is
int(3.5)
Note that this truncates; it doesn't round.
Maybe int(eval('3.5'))
Does anybody know how Python manage internally int and long types?
Does it choose the right type dynamically?
What is the limit for an int?
I am using Python 2.6, Is is different with previous versions?
How should I understand the code below?
>>> print type(65535)
<type 'int'>
>>> print type(65536*65536)
<type 'long'>
Update:
>>> print type(0x7fffffff)
<type 'int'>
>>> print type(0x80000000)
<type 'long'>
int and long were "unified" a few versions back. Before that it was possible to overflow an int through math ops.
3.x has further advanced this by eliminating long altogether and only having int.
Python 2: sys.maxint contains the maximum value a Python int can hold.
On a 64-bit Python 2.7, the size is 24 bytes. Check with sys.getsizeof().
Python 3: sys.maxsize contains the maximum size in bytes a Python int can be.
This will be gigabytes in 32 bits, and exabytes in 64 bits.
Such a large int would have a value similar to 8 to the power of sys.maxsize.
This PEP should help.
Bottom line is that you really shouldn't have to worry about it in python versions > 2.4
Python 2 will automatically set the type based on the size of the value. A guide of max values can be found below.
The Max value of the default Int in Python 2 is 65535, anything above that will be a long
For example:
>> print type(65535)
<type 'int'>
>>> print type(65536*65536)
<type 'long'>
In Python 3 the long datatype has been removed and all integer values are handled by the Int class. The default size of Int will depend on your CPU architecture.
For example:
32 bit systems the default datatype for integers will be 'Int32'
64 bit systems the default datatype for integers will be 'Int64'
The min/max values of each type can be found below:
Int8: [-128,127]
Int16: [-32768,32767]
Int32: [-2147483648,2147483647]
Int64: [-9223372036854775808,9223372036854775807]
Int128: [-170141183460469231731687303715884105728,170141183460469231731687303715884105727]
UInt8: [0,255]
UInt16: [0,65535]
UInt32: [0,4294967295]
UInt64: [0,18446744073709551615]
UInt128: [0,340282366920938463463374607431768211455]
If the size of your Int exceeds the limits mentioned above, python will automatically change it's type and allocate more memory to handle this increase in min/max values. Where in Python 2, it would convert into 'long', it now just converts into the next size of Int.
Example: If you are using a 32 bit operating system, your max value of an Int will be 2147483647 by default. If a value of 2147483648 or more is assigned, the type will be changed to Int64.
There are different ways to check the size of the int and it's memory allocation.
Note: In Python 3, using the built-in type() method will always return <class 'int'> no matter what size Int you are using.
On my machine:
>>> print type(1<<30)
<type 'int'>
>>> print type(1<<31)
<type 'long'>
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'long'>
Python uses ints (32 bit signed integers, I don't know if they are C ints under the hood or not) for values that fit into 32 bit, but automatically switches to longs (arbitrarily large number of bits - i.e. bignums) for anything larger. I'm guessing this speeds things up for smaller values while avoiding any overflows with a seamless transition to bignums.
Interesting. On my 64-bit (i7 Ubuntu) box:
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'int'>
Guess it steps up to 64 bit ints on a larger machine.
Python 2.7.9 auto promotes numbers.
For a case where one is unsure to use int() or long().
>>> a = int("123")
>>> type(a)
<type 'int'>
>>> a = int("111111111111111111111111111111111111111111111111111")
>>> type(a)
<type 'long'>
It manages them because int and long are sibling class definitions. They have appropriate methods for +, -, *, /, etc., that will produce results of the appropriate class.
For example
>>> a=1<<30
>>> type(a)
<type 'int'>
>>> b=a*2
>>> type(b)
<type 'long'>
In this case, the class int has a __mul__ method (the one that implements *) which creates a long result when required.
From python 3.x, the unified integer libraries are even more smarter than older versions. On my (i7 Ubuntu) box I got the following,
>>> type(math.factorial(30))
<class 'int'>
For implementation details refer Include/longintrepr.h, Objects/longobject.c and Modules/mathmodule.c files. The last file is a dynamic module (compiled to an so file). The code is well commented to follow.
Just to continue to all the answers that were given here, especially #James Lanes
the size of the integer type can be expressed by this formula:
total range = (2 ^ bit system)
lower limit = -(2 ^ bit system)*0.5
upper limit = ((2 ^ bit system)*0.5) - 1