Python: return float 1.0 as int 1 but float 1.5 as float 1.5 [duplicate]
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
This question already has an answer here:
How to check if a float value is a whole number
11 answers
How to make python print 1 as opposed to 1.0
3 answers
In Python is there a way to turn 1.0 into a integer 1 while the same function ignores 1.5 and leaves it as a float?
Right now, int() will turn 1.0 into 1 but it will also round 1.5 down to 1, which is not what I want.
python floating-point integer
marked as duplicate by Martijn Pieters♦
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
|
show 6 more comments
This question already has an answer here:
How to check if a float value is a whole number
11 answers
How to make python print 1 as opposed to 1.0
3 answers
In Python is there a way to turn 1.0 into a integer 1 while the same function ignores 1.5 and leaves it as a float?
Right now, int() will turn 1.0 into 1 but it will also round 1.5 down to 1, which is not what I want.
python floating-point integer
marked as duplicate by Martijn Pieters♦
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
4
one way could be to check the float usingis_integer()if that passes, convert it toint?
– DirtyBit
Apr 4 at 7:47
7
Floats are approximations,1.0could actually be1.00000000000001or0.999999999999.
– Barmar
Apr 4 at 7:49
6
Note that because of duck typing, this passage you want to achieve is probably out of place or useless, depending on context.
– Federico S
Apr 4 at 7:52
13
Please specify your exact requirements in words/rules rather than just with a single example!
– Lightness Races in Orbit
Apr 4 at 10:35
5
def f(x): if x == 1.0: return 1 else return 1.5
– Bakuriu
Apr 4 at 20:26
|
show 6 more comments
This question already has an answer here:
How to check if a float value is a whole number
11 answers
How to make python print 1 as opposed to 1.0
3 answers
In Python is there a way to turn 1.0 into a integer 1 while the same function ignores 1.5 and leaves it as a float?
Right now, int() will turn 1.0 into 1 but it will also round 1.5 down to 1, which is not what I want.
python floating-point integer
This question already has an answer here:
How to check if a float value is a whole number
11 answers
How to make python print 1 as opposed to 1.0
3 answers
In Python is there a way to turn 1.0 into a integer 1 while the same function ignores 1.5 and leaves it as a float?
Right now, int() will turn 1.0 into 1 but it will also round 1.5 down to 1, which is not what I want.
This question already has an answer here:
How to check if a float value is a whole number
11 answers
How to make python print 1 as opposed to 1.0
3 answers
python floating-point integer
python floating-point integer
edited 19 hours ago
U9-Forward
18.7k51744
18.7k51744
asked Apr 4 at 7:46
Raymond ShenRaymond Shen
17424
17424
marked as duplicate by Martijn Pieters♦
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by Martijn Pieters♦
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
yesterday
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
4
one way could be to check the float usingis_integer()if that passes, convert it toint?
– DirtyBit
Apr 4 at 7:47
7
Floats are approximations,1.0could actually be1.00000000000001or0.999999999999.
– Barmar
Apr 4 at 7:49
6
Note that because of duck typing, this passage you want to achieve is probably out of place or useless, depending on context.
– Federico S
Apr 4 at 7:52
13
Please specify your exact requirements in words/rules rather than just with a single example!
– Lightness Races in Orbit
Apr 4 at 10:35
5
def f(x): if x == 1.0: return 1 else return 1.5
– Bakuriu
Apr 4 at 20:26
|
show 6 more comments
4
one way could be to check the float usingis_integer()if that passes, convert it toint?
– DirtyBit
Apr 4 at 7:47
7
Floats are approximations,1.0could actually be1.00000000000001or0.999999999999.
– Barmar
Apr 4 at 7:49
6
Note that because of duck typing, this passage you want to achieve is probably out of place or useless, depending on context.
– Federico S
Apr 4 at 7:52
13
Please specify your exact requirements in words/rules rather than just with a single example!
– Lightness Races in Orbit
Apr 4 at 10:35
5
def f(x): if x == 1.0: return 1 else return 1.5
– Bakuriu
Apr 4 at 20:26
4
4
one way could be to check the float using
is_integer() if that passes, convert it to int?– DirtyBit
Apr 4 at 7:47
one way could be to check the float using
is_integer() if that passes, convert it to int?– DirtyBit
Apr 4 at 7:47
7
7
Floats are approximations,
1.0 could actually be 1.00000000000001 or 0.999999999999.– Barmar
Apr 4 at 7:49
Floats are approximations,
1.0 could actually be 1.00000000000001 or 0.999999999999.– Barmar
Apr 4 at 7:49
6
6
Note that because of duck typing, this passage you want to achieve is probably out of place or useless, depending on context.
– Federico S
Apr 4 at 7:52
Note that because of duck typing, this passage you want to achieve is probably out of place or useless, depending on context.
– Federico S
Apr 4 at 7:52
13
13
Please specify your exact requirements in words/rules rather than just with a single example!
– Lightness Races in Orbit
Apr 4 at 10:35
Please specify your exact requirements in words/rules rather than just with a single example!
– Lightness Races in Orbit
Apr 4 at 10:35
5
5
def f(x): if x == 1.0: return 1 else return 1.5– Bakuriu
Apr 4 at 20:26
def f(x): if x == 1.0: return 1 else return 1.5– Bakuriu
Apr 4 at 20:26
|
show 6 more comments
11 Answers
11
active
oldest
votes
Continuing from the comments above:
Using is_integer():
Example from the docs:
>>> (1.5).is_integer()
False
>>> (1.0).is_integer()
True
>>> (1.4142135623730951).is_integer()
False
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
INPUT:
s = [1.5, 1.0, 2.5, 3.54, 1.0, 4.4, 2.0]
Hence:
print([int(x) if x.is_integer() else x for x in s])
Wrapped in a function:
def func(s):
return [int(x) if x.is_integer() else x for x in s]
print(func(s))
If you do not want any import:
def func(s):
return [int(x) if x == int(x) else x for x in s]
print(func(s))
Using map() with lambda function and the iter s:
print(list(map(lambda x: int(x) if x.is_integer() else x, s)))
OR
print(list(map(lambda x: int(x) if int(x) == x else x, s)))
OUTPUT:
[1.5, 1, 2.5, 3.54, 1, 4.4, 2]
15
If anyone is curious about about the limits of is_integer() and how far away from 1.0 a floating point number can be and still be considered an integer, I wrote a short script to find the limit. It's a very small number, much more precision than I have ever needed for anything. (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656251e-16).is_integer() returns False, but (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656250e-16).is_integer() returns True.
– Josh Davis
Apr 4 at 18:33
24
@JoshDavis That's just about rounding to1.0vs.1.0 + sys.float_info.epsilon.
– LegionMammal978
Apr 4 at 19:55
All solutions I see here, based onis_integer, will fail miserably if they receive an integer value, because integers doesn't have that method. To be safe, something like this will help:to_int = lambda x: int(x) if float(x).is_integer() else x
– accdias
Apr 5 at 2:41
4
@accdias: That won't always work either, sincefloathas representational limits whileintdoes not. Passingx = 1 << 1024will cause your code to die with anOverflowError. So now you've got additional checks for safety, or exception handling.
– ShadowRanger
Apr 5 at 3:09
@ShadowRanger, that is true but I'm pretty sure most of people will be never reaching the1 << 1024limit, if ever. On the other hand, I think it is much more feasible to see someone trying to do2 .is_integer()thanfloat(1<<1024). Good info anyway.
– accdias
Apr 5 at 3:57
|
show 1 more comment
In case your goal is to convert numbers to a concise string, you could simply use '%g' ("General Format") for formatting:
>>> '%g' % 1.0
'1'
>>> '%g' % 1
'1'
>>> '%g' % 1.5
'1.5'
>>> '%g' % 0.3
'0.3'
>>> '%g' % 0.9999999999
'1'
You can specify the desired accuracy:
>>> '%.15g' % 0.999999999999999
'0.999999999999999'
>>> '%.2g' % 0.999
'1'
This is great but I had a query yesterday that for some reason I couldn't ask, this would turn0.9to1but considering one only wants1.0to1or2.0to2and not0.9to1or1.9to2. Do we have a workabout in that case? cheers!
– DirtyBit
Apr 5 at 11:13
@DirtyBit: Sorry, I really don't understand the question.'%g' % 0.9is'0.9'and'%g' % 2.0is'2'. Floats are displayed as ints only if they're really close to an int, e.g.0.9999995. But not0.9or0.99
– Eric Duminil
Apr 5 at 11:20
exactly:print('%g' % 0.9999999999) # 1but let's say the req. was to only have1if it was1.0and not0.9999999999?
– DirtyBit
Apr 5 at 11:23
2
@DirtyBit: You can specify the desired accuracy :'%.15g' % 0.999999999999999is'0.999999999999999'and'%.2g' % 0.999is'1'. From this article : Rounding error is the characteristic feature of floating-point computation.
– Eric Duminil
Apr 5 at 11:35
2
Best answer since this is the only valid use case for what the OP wants anyway.
– jpmc26
Apr 7 at 8:59
|
show 3 more comments
float.is_integer is a method on floats that returns whether or not the float represents an integer.
You can just use this function I made called to_int, that uses is_integer to check whether it represents an integer (e.g. 1.0) or not (e.g. 1.5).
If it represents an integer, return int(a), otherwise just return it's original value.
As you see, I am not using elif or else because return returns only once:
def to_int(a):
if a.is_integer():
return int(a)
return a
print(to_int(1.5))
print(to_int(1.0))
Output:
1.5
1
add a comment |
Python floats are approximations, so something that prints as 1.0 is not necessarily exactly 1.0. If you want to see if something is approximately an integer, use a sufficiently small epsilon value.
EPSILON = 0.0001 # Make this smaller or larger depending on desired accuracy
def func(x):
if abs(x - round(x)) < EPSILON:
return round(x)
else:
return x
In general, if you're checking whether a float is == to something, that tends to be a code smell, as floating point values are inherently approximate. It's more appropriate in general to check whether a float is near something, within some epsilon range.
4
While most floating point values are approximations, there are many integers that can be represented exactly. A 64-bit IEEE 754 floating point number (as used in Python and other languages) can represent exactly any signed integer that fits in 53 bits or less. Such integers can be converted 1 to 1 between a 64-bit float and 64-bit integer assuming the integer value could be represented with as little as 53 bits. Addition, subtraction, and multiplication that stays within 53-bits of integer space should yield identical results per IEEE 754 spec.
– penguin359
Apr 4 at 18:04
1
@penguin359 While I agree that integers can be represented exactly in floating point, if you're in the situation that OP is in, you need to ask yourself how close to an integer is "close enough" for your purpose. Is1.0 + 1e-16"close enough"? Is1.0 + 2e-16? It's an important question, as IEEE 754-based "is integer" methods will treat them differently, and you may or may not want to consider1.0 + 2e-16"not an integer" while saying1.0 + 1e-16is one. -- Having an explicit epsilon (versus the implicit one from IEEE 754) makes your desires clearer.
– R.M.
Apr 4 at 19:30
A comment seeming best at this answer: Setting an epsilon works as in the example provided works fine. Alternatively, especially if dealing with cents (currencies in general), I found it more useful to change from Python's default of binary representation to decimal one, as provided by module decimal (docs.python.org/3.7/library/decimal.html). The difference, for example in a loop iterating from -1 to +1 in increments of 0.1 is either passing very close to 0, or right at 0.0 -- without need for an epsilon set (how would you deal with -1.3877787807814457e-16 currency units?).
– Buttonwood
Apr 4 at 19:39
1
"so something that prints as 1.0 is not necessarily exactly 1.0" That depends on the version of python. In modern python3 (IIRC since python 3.2) a float that prints as 1.0 is exactly 1.0. In older versions of python it may not be. Try "print (float(numpy.nextafter(1.0,2)))" to see what happens on your version.
– plugwash
Apr 5 at 13:36
add a comment |
for list of numbers:
def get_int_if_possible(list_of_numbers):
return [int(x) if x == int(x) else x for x in list_of_numbers]
for one number:
def get_int_if_possible(number):
return int(number) if number == int(number) else number
add a comment |
A simple thing you could do is use the modulo operator:
if (myFloat % 1 == 0) // Number is an int
else // numer is not an int
EDIT: Python code
if myFloat % 1 == 0:
# myFloat is an integer.
else:
# myFloat is NOT an integer
2
As he mentioned, this is simply a logic. Not a working code. This should be fine IMO.
– Amit Joshi
Apr 4 at 12:49
Added some Python code (I think). I'd like to know why the downvote? It's a simple solution that works. No weird functions or other constructs required. I didn't think an explanation was necessary, as modulo counts as basic arithmetic. IMO every developer should know what it does or should have the ability to invest 10 seconds into typing "modulo" in to the all-knowing search engine whom I shall not name.
– SimonC
Apr 4 at 13:02
@EricDuminil That was the reason I only added the pseudo-code in the first place. My point was merely that a simple solution is to use the modulo operation. AFAIK it's available in all programming languages. I provided a basic structure which resembles how to use it.
– SimonC
Apr 5 at 7:19
@EricDuminil Added Python code.
– SimonC
Apr 10 at 12:03
add a comment |
What I used to do in the past in C++ is, lets say you have these variables:
float x = 1.5;
float y = 1.0;
Then you could do something like this:
if(x == (int)x)
return 1;
else return 0;
This will return 0 because 1.5 is not equal to 1
if(y == (int)y)
return 1;
else return 0;
This will return 1 because 1.0 is equal to 1
Of course your question is about Python and the function is_integer() should work great, I just thought some people might find this useful.
1
The question was to convert a float to int whenever the float in question has an integer value. AFAIK this is not possible in C++, because you cannot return different values from a function.
– M.Herzkamp
Apr 4 at 11:49
3
@M.Herzkamp you could have aunionthough.
– Baldrickk
Apr 4 at 12:13
And also you could set another integer variable and save the float there if the condition above is met
– Stefan Kostoski
Apr 4 at 12:40
1
The digression on C++ isn't really relevant. You can do the same thing in Python:foo = lambda x: int(x) if int(x) == x else x. (Or in Python 3.8, to avoid the duplicate call toint,lambda x: y if (y:=int(x)) == x else x.
– chepner
Apr 4 at 13:11
1
filterdoesn't modify the values in the list; the function is just a predicate that decides whether or not to select the original value for its output. Usemapinstead.
– chepner
Apr 5 at 11:14
|
show 4 more comments
def your_function(i):
if i.is_integer():
return int(i)
else:
return float(i)
While this may answer the question, it would be very helpful if you could add on what is happening in there and how does it solve the problem, in order to increase the lifetime of your answer and to attract the users looking for the similar solution.
– DirtyBit
Apr 10 at 10:33
strings and floats have a function called is_integer, which returns true if it's a number, and false if anything else (including floats). So, if it's an int, return it as an int. Anything else (it's a float) and return it as a float.
– xcrafter_40
Apr 11 at 1:01
@ xcrafter_40 not as a comment, you may edit your answer to add the explanation. :)
– DirtyBit
Apr 11 at 6:30
add a comment |
The answer to the question as it is put requires comparison of the float value. One must always avoid equality operations on floats. Some form of rounding is a valid approach.
But for this kind of use case, the decimals module is your friend. Decimals have the advantage of absolute accuracy for the values cited in the question compared to floats and also achieve completely reliable results in comparison operations.
add a comment |
divmod alternative:
def f(x):
return x if divmod(x, 1)[1] else int(x)
add a comment |
if you looking for direct approach without using .is_integer() method?
is_integer is a method for float you can check using,
dir(float) #eg dir(1.0)
will list of methods available for float including .is_integer()
Now come to the point...
Direct Approach:
int(float_num) -> will return int so do direct comparison
syntax: int(num) == num -> int(num) otherwise -> num
script: n = int(num) if int(num) == num else num
eg:
num = 1.5
n = int(num) if int(num) == num else num
print n
>>> 1.5
As a function,
>>> def num_con(n):
... return int(n) if int(n) == n else n
Sample Input/output:
>>> num_con(1.0)
1
>>> num_con(1.5)
1.5
>>> num_con(2.5)
2.5
>>> num_con(2.0)
2
>>>
same way for list of numbers,
a) single line:
[int(i) if int(i) == i else i for i in [1.5,2.0,3.2,4.0,5.5]]
b) function reuse:
[num_con(i) for i in [1.5,2.0,3.2,4.0,5.5]] #num_con is a function which we wrote on top
add a comment |
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
Continuing from the comments above:
Using is_integer():
Example from the docs:
>>> (1.5).is_integer()
False
>>> (1.0).is_integer()
True
>>> (1.4142135623730951).is_integer()
False
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
INPUT:
s = [1.5, 1.0, 2.5, 3.54, 1.0, 4.4, 2.0]
Hence:
print([int(x) if x.is_integer() else x for x in s])
Wrapped in a function:
def func(s):
return [int(x) if x.is_integer() else x for x in s]
print(func(s))
If you do not want any import:
def func(s):
return [int(x) if x == int(x) else x for x in s]
print(func(s))
Using map() with lambda function and the iter s:
print(list(map(lambda x: int(x) if x.is_integer() else x, s)))
OR
print(list(map(lambda x: int(x) if int(x) == x else x, s)))
OUTPUT:
[1.5, 1, 2.5, 3.54, 1, 4.4, 2]
15
If anyone is curious about about the limits of is_integer() and how far away from 1.0 a floating point number can be and still be considered an integer, I wrote a short script to find the limit. It's a very small number, much more precision than I have ever needed for anything. (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656251e-16).is_integer() returns False, but (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656250e-16).is_integer() returns True.
– Josh Davis
Apr 4 at 18:33
24
@JoshDavis That's just about rounding to1.0vs.1.0 + sys.float_info.epsilon.
– LegionMammal978
Apr 4 at 19:55
All solutions I see here, based onis_integer, will fail miserably if they receive an integer value, because integers doesn't have that method. To be safe, something like this will help:to_int = lambda x: int(x) if float(x).is_integer() else x
– accdias
Apr 5 at 2:41
4
@accdias: That won't always work either, sincefloathas representational limits whileintdoes not. Passingx = 1 << 1024will cause your code to die with anOverflowError. So now you've got additional checks for safety, or exception handling.
– ShadowRanger
Apr 5 at 3:09
@ShadowRanger, that is true but I'm pretty sure most of people will be never reaching the1 << 1024limit, if ever. On the other hand, I think it is much more feasible to see someone trying to do2 .is_integer()thanfloat(1<<1024). Good info anyway.
– accdias
Apr 5 at 3:57
|
show 1 more comment
Continuing from the comments above:
Using is_integer():
Example from the docs:
>>> (1.5).is_integer()
False
>>> (1.0).is_integer()
True
>>> (1.4142135623730951).is_integer()
False
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
INPUT:
s = [1.5, 1.0, 2.5, 3.54, 1.0, 4.4, 2.0]
Hence:
print([int(x) if x.is_integer() else x for x in s])
Wrapped in a function:
def func(s):
return [int(x) if x.is_integer() else x for x in s]
print(func(s))
If you do not want any import:
def func(s):
return [int(x) if x == int(x) else x for x in s]
print(func(s))
Using map() with lambda function and the iter s:
print(list(map(lambda x: int(x) if x.is_integer() else x, s)))
OR
print(list(map(lambda x: int(x) if int(x) == x else x, s)))
OUTPUT:
[1.5, 1, 2.5, 3.54, 1, 4.4, 2]
15
If anyone is curious about about the limits of is_integer() and how far away from 1.0 a floating point number can be and still be considered an integer, I wrote a short script to find the limit. It's a very small number, much more precision than I have ever needed for anything. (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656251e-16).is_integer() returns False, but (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656250e-16).is_integer() returns True.
– Josh Davis
Apr 4 at 18:33
24
@JoshDavis That's just about rounding to1.0vs.1.0 + sys.float_info.epsilon.
– LegionMammal978
Apr 4 at 19:55
All solutions I see here, based onis_integer, will fail miserably if they receive an integer value, because integers doesn't have that method. To be safe, something like this will help:to_int = lambda x: int(x) if float(x).is_integer() else x
– accdias
Apr 5 at 2:41
4
@accdias: That won't always work either, sincefloathas representational limits whileintdoes not. Passingx = 1 << 1024will cause your code to die with anOverflowError. So now you've got additional checks for safety, or exception handling.
– ShadowRanger
Apr 5 at 3:09
@ShadowRanger, that is true but I'm pretty sure most of people will be never reaching the1 << 1024limit, if ever. On the other hand, I think it is much more feasible to see someone trying to do2 .is_integer()thanfloat(1<<1024). Good info anyway.
– accdias
Apr 5 at 3:57
|
show 1 more comment
Continuing from the comments above:
Using is_integer():
Example from the docs:
>>> (1.5).is_integer()
False
>>> (1.0).is_integer()
True
>>> (1.4142135623730951).is_integer()
False
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
INPUT:
s = [1.5, 1.0, 2.5, 3.54, 1.0, 4.4, 2.0]
Hence:
print([int(x) if x.is_integer() else x for x in s])
Wrapped in a function:
def func(s):
return [int(x) if x.is_integer() else x for x in s]
print(func(s))
If you do not want any import:
def func(s):
return [int(x) if x == int(x) else x for x in s]
print(func(s))
Using map() with lambda function and the iter s:
print(list(map(lambda x: int(x) if x.is_integer() else x, s)))
OR
print(list(map(lambda x: int(x) if int(x) == x else x, s)))
OUTPUT:
[1.5, 1, 2.5, 3.54, 1, 4.4, 2]
Continuing from the comments above:
Using is_integer():
Example from the docs:
>>> (1.5).is_integer()
False
>>> (1.0).is_integer()
True
>>> (1.4142135623730951).is_integer()
False
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
INPUT:
s = [1.5, 1.0, 2.5, 3.54, 1.0, 4.4, 2.0]
Hence:
print([int(x) if x.is_integer() else x for x in s])
Wrapped in a function:
def func(s):
return [int(x) if x.is_integer() else x for x in s]
print(func(s))
If you do not want any import:
def func(s):
return [int(x) if x == int(x) else x for x in s]
print(func(s))
Using map() with lambda function and the iter s:
print(list(map(lambda x: int(x) if x.is_integer() else x, s)))
OR
print(list(map(lambda x: int(x) if int(x) == x else x, s)))
OUTPUT:
[1.5, 1, 2.5, 3.54, 1, 4.4, 2]
edited Apr 7 at 7:37
answered Apr 4 at 7:49
DirtyBitDirtyBit
1
1
15
If anyone is curious about about the limits of is_integer() and how far away from 1.0 a floating point number can be and still be considered an integer, I wrote a short script to find the limit. It's a very small number, much more precision than I have ever needed for anything. (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656251e-16).is_integer() returns False, but (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656250e-16).is_integer() returns True.
– Josh Davis
Apr 4 at 18:33
24
@JoshDavis That's just about rounding to1.0vs.1.0 + sys.float_info.epsilon.
– LegionMammal978
Apr 4 at 19:55
All solutions I see here, based onis_integer, will fail miserably if they receive an integer value, because integers doesn't have that method. To be safe, something like this will help:to_int = lambda x: int(x) if float(x).is_integer() else x
– accdias
Apr 5 at 2:41
4
@accdias: That won't always work either, sincefloathas representational limits whileintdoes not. Passingx = 1 << 1024will cause your code to die with anOverflowError. So now you've got additional checks for safety, or exception handling.
– ShadowRanger
Apr 5 at 3:09
@ShadowRanger, that is true but I'm pretty sure most of people will be never reaching the1 << 1024limit, if ever. On the other hand, I think it is much more feasible to see someone trying to do2 .is_integer()thanfloat(1<<1024). Good info anyway.
– accdias
Apr 5 at 3:57
|
show 1 more comment
15
If anyone is curious about about the limits of is_integer() and how far away from 1.0 a floating point number can be and still be considered an integer, I wrote a short script to find the limit. It's a very small number, much more precision than I have ever needed for anything. (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656251e-16).is_integer() returns False, but (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656250e-16).is_integer() returns True.
– Josh Davis
Apr 4 at 18:33
24
@JoshDavis That's just about rounding to1.0vs.1.0 + sys.float_info.epsilon.
– LegionMammal978
Apr 4 at 19:55
All solutions I see here, based onis_integer, will fail miserably if they receive an integer value, because integers doesn't have that method. To be safe, something like this will help:to_int = lambda x: int(x) if float(x).is_integer() else x
– accdias
Apr 5 at 2:41
4
@accdias: That won't always work either, sincefloathas representational limits whileintdoes not. Passingx = 1 << 1024will cause your code to die with anOverflowError. So now you've got additional checks for safety, or exception handling.
– ShadowRanger
Apr 5 at 3:09
@ShadowRanger, that is true but I'm pretty sure most of people will be never reaching the1 << 1024limit, if ever. On the other hand, I think it is much more feasible to see someone trying to do2 .is_integer()thanfloat(1<<1024). Good info anyway.
– accdias
Apr 5 at 3:57
15
15
If anyone is curious about about the limits of is_integer() and how far away from 1.0 a floating point number can be and still be considered an integer, I wrote a short script to find the limit. It's a very small number, much more precision than I have ever needed for anything. (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656251e-16).is_integer() returns False, but (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656250e-16).is_integer() returns True.
– Josh Davis
Apr 4 at 18:33
If anyone is curious about about the limits of is_integer() and how far away from 1.0 a floating point number can be and still be considered an integer, I wrote a short script to find the limit. It's a very small number, much more precision than I have ever needed for anything. (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656251e-16).is_integer() returns False, but (1.0 + 1.1102230246251566636831481088739149080825883254353483864385054857848444953560829162597656250e-16).is_integer() returns True.
– Josh Davis
Apr 4 at 18:33
24
24
@JoshDavis That's just about rounding to
1.0 vs. 1.0 + sys.float_info.epsilon.– LegionMammal978
Apr 4 at 19:55
@JoshDavis That's just about rounding to
1.0 vs. 1.0 + sys.float_info.epsilon.– LegionMammal978
Apr 4 at 19:55
All solutions I see here, based on
is_integer, will fail miserably if they receive an integer value, because integers doesn't have that method. To be safe, something like this will help: to_int = lambda x: int(x) if float(x).is_integer() else x– accdias
Apr 5 at 2:41
All solutions I see here, based on
is_integer, will fail miserably if they receive an integer value, because integers doesn't have that method. To be safe, something like this will help: to_int = lambda x: int(x) if float(x).is_integer() else x– accdias
Apr 5 at 2:41
4
4
@accdias: That won't always work either, since
float has representational limits while int does not. Passing x = 1 << 1024 will cause your code to die with an OverflowError. So now you've got additional checks for safety, or exception handling.– ShadowRanger
Apr 5 at 3:09
@accdias: That won't always work either, since
float has representational limits while int does not. Passing x = 1 << 1024 will cause your code to die with an OverflowError. So now you've got additional checks for safety, or exception handling.– ShadowRanger
Apr 5 at 3:09
@ShadowRanger, that is true but I'm pretty sure most of people will be never reaching the
1 << 1024 limit, if ever. On the other hand, I think it is much more feasible to see someone trying to do 2 .is_integer() than float(1<<1024). Good info anyway.– accdias
Apr 5 at 3:57
@ShadowRanger, that is true but I'm pretty sure most of people will be never reaching the
1 << 1024 limit, if ever. On the other hand, I think it is much more feasible to see someone trying to do 2 .is_integer() than float(1<<1024). Good info anyway.– accdias
Apr 5 at 3:57
|
show 1 more comment
In case your goal is to convert numbers to a concise string, you could simply use '%g' ("General Format") for formatting:
>>> '%g' % 1.0
'1'
>>> '%g' % 1
'1'
>>> '%g' % 1.5
'1.5'
>>> '%g' % 0.3
'0.3'
>>> '%g' % 0.9999999999
'1'
You can specify the desired accuracy:
>>> '%.15g' % 0.999999999999999
'0.999999999999999'
>>> '%.2g' % 0.999
'1'
This is great but I had a query yesterday that for some reason I couldn't ask, this would turn0.9to1but considering one only wants1.0to1or2.0to2and not0.9to1or1.9to2. Do we have a workabout in that case? cheers!
– DirtyBit
Apr 5 at 11:13
@DirtyBit: Sorry, I really don't understand the question.'%g' % 0.9is'0.9'and'%g' % 2.0is'2'. Floats are displayed as ints only if they're really close to an int, e.g.0.9999995. But not0.9or0.99
– Eric Duminil
Apr 5 at 11:20
exactly:print('%g' % 0.9999999999) # 1but let's say the req. was to only have1if it was1.0and not0.9999999999?
– DirtyBit
Apr 5 at 11:23
2
@DirtyBit: You can specify the desired accuracy :'%.15g' % 0.999999999999999is'0.999999999999999'and'%.2g' % 0.999is'1'. From this article : Rounding error is the characteristic feature of floating-point computation.
– Eric Duminil
Apr 5 at 11:35
2
Best answer since this is the only valid use case for what the OP wants anyway.
– jpmc26
Apr 7 at 8:59
|
show 3 more comments
In case your goal is to convert numbers to a concise string, you could simply use '%g' ("General Format") for formatting:
>>> '%g' % 1.0
'1'
>>> '%g' % 1
'1'
>>> '%g' % 1.5
'1.5'
>>> '%g' % 0.3
'0.3'
>>> '%g' % 0.9999999999
'1'
You can specify the desired accuracy:
>>> '%.15g' % 0.999999999999999
'0.999999999999999'
>>> '%.2g' % 0.999
'1'
This is great but I had a query yesterday that for some reason I couldn't ask, this would turn0.9to1but considering one only wants1.0to1or2.0to2and not0.9to1or1.9to2. Do we have a workabout in that case? cheers!
– DirtyBit
Apr 5 at 11:13
@DirtyBit: Sorry, I really don't understand the question.'%g' % 0.9is'0.9'and'%g' % 2.0is'2'. Floats are displayed as ints only if they're really close to an int, e.g.0.9999995. But not0.9or0.99
– Eric Duminil
Apr 5 at 11:20
exactly:print('%g' % 0.9999999999) # 1but let's say the req. was to only have1if it was1.0and not0.9999999999?
– DirtyBit
Apr 5 at 11:23
2
@DirtyBit: You can specify the desired accuracy :'%.15g' % 0.999999999999999is'0.999999999999999'and'%.2g' % 0.999is'1'. From this article : Rounding error is the characteristic feature of floating-point computation.
– Eric Duminil
Apr 5 at 11:35
2
Best answer since this is the only valid use case for what the OP wants anyway.
– jpmc26
Apr 7 at 8:59
|
show 3 more comments
In case your goal is to convert numbers to a concise string, you could simply use '%g' ("General Format") for formatting:
>>> '%g' % 1.0
'1'
>>> '%g' % 1
'1'
>>> '%g' % 1.5
'1.5'
>>> '%g' % 0.3
'0.3'
>>> '%g' % 0.9999999999
'1'
You can specify the desired accuracy:
>>> '%.15g' % 0.999999999999999
'0.999999999999999'
>>> '%.2g' % 0.999
'1'
In case your goal is to convert numbers to a concise string, you could simply use '%g' ("General Format") for formatting:
>>> '%g' % 1.0
'1'
>>> '%g' % 1
'1'
>>> '%g' % 1.5
'1.5'
>>> '%g' % 0.3
'0.3'
>>> '%g' % 0.9999999999
'1'
You can specify the desired accuracy:
>>> '%.15g' % 0.999999999999999
'0.999999999999999'
>>> '%.2g' % 0.999
'1'
edited Apr 5 at 11:36
answered Apr 4 at 12:23
Eric DuminilEric Duminil
41.1k63472
41.1k63472
This is great but I had a query yesterday that for some reason I couldn't ask, this would turn0.9to1but considering one only wants1.0to1or2.0to2and not0.9to1or1.9to2. Do we have a workabout in that case? cheers!
– DirtyBit
Apr 5 at 11:13
@DirtyBit: Sorry, I really don't understand the question.'%g' % 0.9is'0.9'and'%g' % 2.0is'2'. Floats are displayed as ints only if they're really close to an int, e.g.0.9999995. But not0.9or0.99
– Eric Duminil
Apr 5 at 11:20
exactly:print('%g' % 0.9999999999) # 1but let's say the req. was to only have1if it was1.0and not0.9999999999?
– DirtyBit
Apr 5 at 11:23
2
@DirtyBit: You can specify the desired accuracy :'%.15g' % 0.999999999999999is'0.999999999999999'and'%.2g' % 0.999is'1'. From this article : Rounding error is the characteristic feature of floating-point computation.
– Eric Duminil
Apr 5 at 11:35
2
Best answer since this is the only valid use case for what the OP wants anyway.
– jpmc26
Apr 7 at 8:59
|
show 3 more comments
This is great but I had a query yesterday that for some reason I couldn't ask, this would turn0.9to1but considering one only wants1.0to1or2.0to2and not0.9to1or1.9to2. Do we have a workabout in that case? cheers!
– DirtyBit
Apr 5 at 11:13
@DirtyBit: Sorry, I really don't understand the question.'%g' % 0.9is'0.9'and'%g' % 2.0is'2'. Floats are displayed as ints only if they're really close to an int, e.g.0.9999995. But not0.9or0.99
– Eric Duminil
Apr 5 at 11:20
exactly:print('%g' % 0.9999999999) # 1but let's say the req. was to only have1if it was1.0and not0.9999999999?
– DirtyBit
Apr 5 at 11:23
2
@DirtyBit: You can specify the desired accuracy :'%.15g' % 0.999999999999999is'0.999999999999999'and'%.2g' % 0.999is'1'. From this article : Rounding error is the characteristic feature of floating-point computation.
– Eric Duminil
Apr 5 at 11:35
2
Best answer since this is the only valid use case for what the OP wants anyway.
– jpmc26
Apr 7 at 8:59
This is great but I had a query yesterday that for some reason I couldn't ask, this would turn
0.9 to 1 but considering one only wants 1.0 to 1 or 2.0 to 2 and not 0.9 to 1 or 1.9 to 2. Do we have a workabout in that case? cheers!– DirtyBit
Apr 5 at 11:13
This is great but I had a query yesterday that for some reason I couldn't ask, this would turn
0.9 to 1 but considering one only wants 1.0 to 1 or 2.0 to 2 and not 0.9 to 1 or 1.9 to 2. Do we have a workabout in that case? cheers!– DirtyBit
Apr 5 at 11:13
@DirtyBit: Sorry, I really don't understand the question.
'%g' % 0.9 is '0.9' and '%g' % 2.0 is '2'. Floats are displayed as ints only if they're really close to an int, e.g. 0.9999995. But not 0.9 or 0.99– Eric Duminil
Apr 5 at 11:20
@DirtyBit: Sorry, I really don't understand the question.
'%g' % 0.9 is '0.9' and '%g' % 2.0 is '2'. Floats are displayed as ints only if they're really close to an int, e.g. 0.9999995. But not 0.9 or 0.99– Eric Duminil
Apr 5 at 11:20
exactly:
print('%g' % 0.9999999999) # 1 but let's say the req. was to only have 1 if it was 1.0 and not 0.9999999999?– DirtyBit
Apr 5 at 11:23
exactly:
print('%g' % 0.9999999999) # 1 but let's say the req. was to only have 1 if it was 1.0 and not 0.9999999999?– DirtyBit
Apr 5 at 11:23
2
2
@DirtyBit: You can specify the desired accuracy :
'%.15g' % 0.999999999999999 is '0.999999999999999' and '%.2g' % 0.999is '1'. From this article : Rounding error is the characteristic feature of floating-point computation.– Eric Duminil
Apr 5 at 11:35
@DirtyBit: You can specify the desired accuracy :
'%.15g' % 0.999999999999999 is '0.999999999999999' and '%.2g' % 0.999is '1'. From this article : Rounding error is the characteristic feature of floating-point computation.– Eric Duminil
Apr 5 at 11:35
2
2
Best answer since this is the only valid use case for what the OP wants anyway.
– jpmc26
Apr 7 at 8:59
Best answer since this is the only valid use case for what the OP wants anyway.
– jpmc26
Apr 7 at 8:59
|
show 3 more comments
float.is_integer is a method on floats that returns whether or not the float represents an integer.
You can just use this function I made called to_int, that uses is_integer to check whether it represents an integer (e.g. 1.0) or not (e.g. 1.5).
If it represents an integer, return int(a), otherwise just return it's original value.
As you see, I am not using elif or else because return returns only once:
def to_int(a):
if a.is_integer():
return int(a)
return a
print(to_int(1.5))
print(to_int(1.0))
Output:
1.5
1
add a comment |
float.is_integer is a method on floats that returns whether or not the float represents an integer.
You can just use this function I made called to_int, that uses is_integer to check whether it represents an integer (e.g. 1.0) or not (e.g. 1.5).
If it represents an integer, return int(a), otherwise just return it's original value.
As you see, I am not using elif or else because return returns only once:
def to_int(a):
if a.is_integer():
return int(a)
return a
print(to_int(1.5))
print(to_int(1.0))
Output:
1.5
1
add a comment |
float.is_integer is a method on floats that returns whether or not the float represents an integer.
You can just use this function I made called to_int, that uses is_integer to check whether it represents an integer (e.g. 1.0) or not (e.g. 1.5).
If it represents an integer, return int(a), otherwise just return it's original value.
As you see, I am not using elif or else because return returns only once:
def to_int(a):
if a.is_integer():
return int(a)
return a
print(to_int(1.5))
print(to_int(1.0))
Output:
1.5
1
float.is_integer is a method on floats that returns whether or not the float represents an integer.
You can just use this function I made called to_int, that uses is_integer to check whether it represents an integer (e.g. 1.0) or not (e.g. 1.5).
If it represents an integer, return int(a), otherwise just return it's original value.
As you see, I am not using elif or else because return returns only once:
def to_int(a):
if a.is_integer():
return int(a)
return a
print(to_int(1.5))
print(to_int(1.0))
Output:
1.5
1
edited 19 hours ago
answered Apr 4 at 7:49
U9-ForwardU9-Forward
18.7k51744
18.7k51744
add a comment |
add a comment |
Python floats are approximations, so something that prints as 1.0 is not necessarily exactly 1.0. If you want to see if something is approximately an integer, use a sufficiently small epsilon value.
EPSILON = 0.0001 # Make this smaller or larger depending on desired accuracy
def func(x):
if abs(x - round(x)) < EPSILON:
return round(x)
else:
return x
In general, if you're checking whether a float is == to something, that tends to be a code smell, as floating point values are inherently approximate. It's more appropriate in general to check whether a float is near something, within some epsilon range.
4
While most floating point values are approximations, there are many integers that can be represented exactly. A 64-bit IEEE 754 floating point number (as used in Python and other languages) can represent exactly any signed integer that fits in 53 bits or less. Such integers can be converted 1 to 1 between a 64-bit float and 64-bit integer assuming the integer value could be represented with as little as 53 bits. Addition, subtraction, and multiplication that stays within 53-bits of integer space should yield identical results per IEEE 754 spec.
– penguin359
Apr 4 at 18:04
1
@penguin359 While I agree that integers can be represented exactly in floating point, if you're in the situation that OP is in, you need to ask yourself how close to an integer is "close enough" for your purpose. Is1.0 + 1e-16"close enough"? Is1.0 + 2e-16? It's an important question, as IEEE 754-based "is integer" methods will treat them differently, and you may or may not want to consider1.0 + 2e-16"not an integer" while saying1.0 + 1e-16is one. -- Having an explicit epsilon (versus the implicit one from IEEE 754) makes your desires clearer.
– R.M.
Apr 4 at 19:30
A comment seeming best at this answer: Setting an epsilon works as in the example provided works fine. Alternatively, especially if dealing with cents (currencies in general), I found it more useful to change from Python's default of binary representation to decimal one, as provided by module decimal (docs.python.org/3.7/library/decimal.html). The difference, for example in a loop iterating from -1 to +1 in increments of 0.1 is either passing very close to 0, or right at 0.0 -- without need for an epsilon set (how would you deal with -1.3877787807814457e-16 currency units?).
– Buttonwood
Apr 4 at 19:39
1
"so something that prints as 1.0 is not necessarily exactly 1.0" That depends on the version of python. In modern python3 (IIRC since python 3.2) a float that prints as 1.0 is exactly 1.0. In older versions of python it may not be. Try "print (float(numpy.nextafter(1.0,2)))" to see what happens on your version.
– plugwash
Apr 5 at 13:36
add a comment |
Python floats are approximations, so something that prints as 1.0 is not necessarily exactly 1.0. If you want to see if something is approximately an integer, use a sufficiently small epsilon value.
EPSILON = 0.0001 # Make this smaller or larger depending on desired accuracy
def func(x):
if abs(x - round(x)) < EPSILON:
return round(x)
else:
return x
In general, if you're checking whether a float is == to something, that tends to be a code smell, as floating point values are inherently approximate. It's more appropriate in general to check whether a float is near something, within some epsilon range.
4
While most floating point values are approximations, there are many integers that can be represented exactly. A 64-bit IEEE 754 floating point number (as used in Python and other languages) can represent exactly any signed integer that fits in 53 bits or less. Such integers can be converted 1 to 1 between a 64-bit float and 64-bit integer assuming the integer value could be represented with as little as 53 bits. Addition, subtraction, and multiplication that stays within 53-bits of integer space should yield identical results per IEEE 754 spec.
– penguin359
Apr 4 at 18:04
1
@penguin359 While I agree that integers can be represented exactly in floating point, if you're in the situation that OP is in, you need to ask yourself how close to an integer is "close enough" for your purpose. Is1.0 + 1e-16"close enough"? Is1.0 + 2e-16? It's an important question, as IEEE 754-based "is integer" methods will treat them differently, and you may or may not want to consider1.0 + 2e-16"not an integer" while saying1.0 + 1e-16is one. -- Having an explicit epsilon (versus the implicit one from IEEE 754) makes your desires clearer.
– R.M.
Apr 4 at 19:30
A comment seeming best at this answer: Setting an epsilon works as in the example provided works fine. Alternatively, especially if dealing with cents (currencies in general), I found it more useful to change from Python's default of binary representation to decimal one, as provided by module decimal (docs.python.org/3.7/library/decimal.html). The difference, for example in a loop iterating from -1 to +1 in increments of 0.1 is either passing very close to 0, or right at 0.0 -- without need for an epsilon set (how would you deal with -1.3877787807814457e-16 currency units?).
– Buttonwood
Apr 4 at 19:39
1
"so something that prints as 1.0 is not necessarily exactly 1.0" That depends on the version of python. In modern python3 (IIRC since python 3.2) a float that prints as 1.0 is exactly 1.0. In older versions of python it may not be. Try "print (float(numpy.nextafter(1.0,2)))" to see what happens on your version.
– plugwash
Apr 5 at 13:36
add a comment |
Python floats are approximations, so something that prints as 1.0 is not necessarily exactly 1.0. If you want to see if something is approximately an integer, use a sufficiently small epsilon value.
EPSILON = 0.0001 # Make this smaller or larger depending on desired accuracy
def func(x):
if abs(x - round(x)) < EPSILON:
return round(x)
else:
return x
In general, if you're checking whether a float is == to something, that tends to be a code smell, as floating point values are inherently approximate. It's more appropriate in general to check whether a float is near something, within some epsilon range.
Python floats are approximations, so something that prints as 1.0 is not necessarily exactly 1.0. If you want to see if something is approximately an integer, use a sufficiently small epsilon value.
EPSILON = 0.0001 # Make this smaller or larger depending on desired accuracy
def func(x):
if abs(x - round(x)) < EPSILON:
return round(x)
else:
return x
In general, if you're checking whether a float is == to something, that tends to be a code smell, as floating point values are inherently approximate. It's more appropriate in general to check whether a float is near something, within some epsilon range.
edited Apr 4 at 13:36
answered Apr 4 at 13:33
Silvio MayoloSilvio Mayolo
14.9k22654
14.9k22654
4
While most floating point values are approximations, there are many integers that can be represented exactly. A 64-bit IEEE 754 floating point number (as used in Python and other languages) can represent exactly any signed integer that fits in 53 bits or less. Such integers can be converted 1 to 1 between a 64-bit float and 64-bit integer assuming the integer value could be represented with as little as 53 bits. Addition, subtraction, and multiplication that stays within 53-bits of integer space should yield identical results per IEEE 754 spec.
– penguin359
Apr 4 at 18:04
1
@penguin359 While I agree that integers can be represented exactly in floating point, if you're in the situation that OP is in, you need to ask yourself how close to an integer is "close enough" for your purpose. Is1.0 + 1e-16"close enough"? Is1.0 + 2e-16? It's an important question, as IEEE 754-based "is integer" methods will treat them differently, and you may or may not want to consider1.0 + 2e-16"not an integer" while saying1.0 + 1e-16is one. -- Having an explicit epsilon (versus the implicit one from IEEE 754) makes your desires clearer.
– R.M.
Apr 4 at 19:30
A comment seeming best at this answer: Setting an epsilon works as in the example provided works fine. Alternatively, especially if dealing with cents (currencies in general), I found it more useful to change from Python's default of binary representation to decimal one, as provided by module decimal (docs.python.org/3.7/library/decimal.html). The difference, for example in a loop iterating from -1 to +1 in increments of 0.1 is either passing very close to 0, or right at 0.0 -- without need for an epsilon set (how would you deal with -1.3877787807814457e-16 currency units?).
– Buttonwood
Apr 4 at 19:39
1
"so something that prints as 1.0 is not necessarily exactly 1.0" That depends on the version of python. In modern python3 (IIRC since python 3.2) a float that prints as 1.0 is exactly 1.0. In older versions of python it may not be. Try "print (float(numpy.nextafter(1.0,2)))" to see what happens on your version.
– plugwash
Apr 5 at 13:36
add a comment |
4
While most floating point values are approximations, there are many integers that can be represented exactly. A 64-bit IEEE 754 floating point number (as used in Python and other languages) can represent exactly any signed integer that fits in 53 bits or less. Such integers can be converted 1 to 1 between a 64-bit float and 64-bit integer assuming the integer value could be represented with as little as 53 bits. Addition, subtraction, and multiplication that stays within 53-bits of integer space should yield identical results per IEEE 754 spec.
– penguin359
Apr 4 at 18:04
1
@penguin359 While I agree that integers can be represented exactly in floating point, if you're in the situation that OP is in, you need to ask yourself how close to an integer is "close enough" for your purpose. Is1.0 + 1e-16"close enough"? Is1.0 + 2e-16? It's an important question, as IEEE 754-based "is integer" methods will treat them differently, and you may or may not want to consider1.0 + 2e-16"not an integer" while saying1.0 + 1e-16is one. -- Having an explicit epsilon (versus the implicit one from IEEE 754) makes your desires clearer.
– R.M.
Apr 4 at 19:30
A comment seeming best at this answer: Setting an epsilon works as in the example provided works fine. Alternatively, especially if dealing with cents (currencies in general), I found it more useful to change from Python's default of binary representation to decimal one, as provided by module decimal (docs.python.org/3.7/library/decimal.html). The difference, for example in a loop iterating from -1 to +1 in increments of 0.1 is either passing very close to 0, or right at 0.0 -- without need for an epsilon set (how would you deal with -1.3877787807814457e-16 currency units?).
– Buttonwood
Apr 4 at 19:39
1
"so something that prints as 1.0 is not necessarily exactly 1.0" That depends on the version of python. In modern python3 (IIRC since python 3.2) a float that prints as 1.0 is exactly 1.0. In older versions of python it may not be. Try "print (float(numpy.nextafter(1.0,2)))" to see what happens on your version.
– plugwash
Apr 5 at 13:36
4
4
While most floating point values are approximations, there are many integers that can be represented exactly. A 64-bit IEEE 754 floating point number (as used in Python and other languages) can represent exactly any signed integer that fits in 53 bits or less. Such integers can be converted 1 to 1 between a 64-bit float and 64-bit integer assuming the integer value could be represented with as little as 53 bits. Addition, subtraction, and multiplication that stays within 53-bits of integer space should yield identical results per IEEE 754 spec.
– penguin359
Apr 4 at 18:04
While most floating point values are approximations, there are many integers that can be represented exactly. A 64-bit IEEE 754 floating point number (as used in Python and other languages) can represent exactly any signed integer that fits in 53 bits or less. Such integers can be converted 1 to 1 between a 64-bit float and 64-bit integer assuming the integer value could be represented with as little as 53 bits. Addition, subtraction, and multiplication that stays within 53-bits of integer space should yield identical results per IEEE 754 spec.
– penguin359
Apr 4 at 18:04
1
1
@penguin359 While I agree that integers can be represented exactly in floating point, if you're in the situation that OP is in, you need to ask yourself how close to an integer is "close enough" for your purpose. Is
1.0 + 1e-16 "close enough"? Is 1.0 + 2e-16? It's an important question, as IEEE 754-based "is integer" methods will treat them differently, and you may or may not want to consider 1.0 + 2e-16 "not an integer" while saying 1.0 + 1e-16 is one. -- Having an explicit epsilon (versus the implicit one from IEEE 754) makes your desires clearer.– R.M.
Apr 4 at 19:30
@penguin359 While I agree that integers can be represented exactly in floating point, if you're in the situation that OP is in, you need to ask yourself how close to an integer is "close enough" for your purpose. Is
1.0 + 1e-16 "close enough"? Is 1.0 + 2e-16? It's an important question, as IEEE 754-based "is integer" methods will treat them differently, and you may or may not want to consider 1.0 + 2e-16 "not an integer" while saying 1.0 + 1e-16 is one. -- Having an explicit epsilon (versus the implicit one from IEEE 754) makes your desires clearer.– R.M.
Apr 4 at 19:30
A comment seeming best at this answer: Setting an epsilon works as in the example provided works fine. Alternatively, especially if dealing with cents (currencies in general), I found it more useful to change from Python's default of binary representation to decimal one, as provided by module decimal (docs.python.org/3.7/library/decimal.html). The difference, for example in a loop iterating from -1 to +1 in increments of 0.1 is either passing very close to 0, or right at 0.0 -- without need for an epsilon set (how would you deal with -1.3877787807814457e-16 currency units?).
– Buttonwood
Apr 4 at 19:39
A comment seeming best at this answer: Setting an epsilon works as in the example provided works fine. Alternatively, especially if dealing with cents (currencies in general), I found it more useful to change from Python's default of binary representation to decimal one, as provided by module decimal (docs.python.org/3.7/library/decimal.html). The difference, for example in a loop iterating from -1 to +1 in increments of 0.1 is either passing very close to 0, or right at 0.0 -- without need for an epsilon set (how would you deal with -1.3877787807814457e-16 currency units?).
– Buttonwood
Apr 4 at 19:39
1
1
"so something that prints as 1.0 is not necessarily exactly 1.0" That depends on the version of python. In modern python3 (IIRC since python 3.2) a float that prints as 1.0 is exactly 1.0. In older versions of python it may not be. Try "print (float(numpy.nextafter(1.0,2)))" to see what happens on your version.
– plugwash
Apr 5 at 13:36
"so something that prints as 1.0 is not necessarily exactly 1.0" That depends on the version of python. In modern python3 (IIRC since python 3.2) a float that prints as 1.0 is exactly 1.0. In older versions of python it may not be. Try "print (float(numpy.nextafter(1.0,2)))" to see what happens on your version.
– plugwash
Apr 5 at 13:36
add a comment |
for list of numbers:
def get_int_if_possible(list_of_numbers):
return [int(x) if x == int(x) else x for x in list_of_numbers]
for one number:
def get_int_if_possible(number):
return int(number) if number == int(number) else number
add a comment |
for list of numbers:
def get_int_if_possible(list_of_numbers):
return [int(x) if x == int(x) else x for x in list_of_numbers]
for one number:
def get_int_if_possible(number):
return int(number) if number == int(number) else number
add a comment |
for list of numbers:
def get_int_if_possible(list_of_numbers):
return [int(x) if x == int(x) else x for x in list_of_numbers]
for one number:
def get_int_if_possible(number):
return int(number) if number == int(number) else number
for list of numbers:
def get_int_if_possible(list_of_numbers):
return [int(x) if x == int(x) else x for x in list_of_numbers]
for one number:
def get_int_if_possible(number):
return int(number) if number == int(number) else number
answered Apr 7 at 9:34
Baruch G.Baruch G.
397
397
add a comment |
add a comment |
A simple thing you could do is use the modulo operator:
if (myFloat % 1 == 0) // Number is an int
else // numer is not an int
EDIT: Python code
if myFloat % 1 == 0:
# myFloat is an integer.
else:
# myFloat is NOT an integer
2
As he mentioned, this is simply a logic. Not a working code. This should be fine IMO.
– Amit Joshi
Apr 4 at 12:49
Added some Python code (I think). I'd like to know why the downvote? It's a simple solution that works. No weird functions or other constructs required. I didn't think an explanation was necessary, as modulo counts as basic arithmetic. IMO every developer should know what it does or should have the ability to invest 10 seconds into typing "modulo" in to the all-knowing search engine whom I shall not name.
– SimonC
Apr 4 at 13:02
@EricDuminil That was the reason I only added the pseudo-code in the first place. My point was merely that a simple solution is to use the modulo operation. AFAIK it's available in all programming languages. I provided a basic structure which resembles how to use it.
– SimonC
Apr 5 at 7:19
@EricDuminil Added Python code.
– SimonC
Apr 10 at 12:03
add a comment |
A simple thing you could do is use the modulo operator:
if (myFloat % 1 == 0) // Number is an int
else // numer is not an int
EDIT: Python code
if myFloat % 1 == 0:
# myFloat is an integer.
else:
# myFloat is NOT an integer
2
As he mentioned, this is simply a logic. Not a working code. This should be fine IMO.
– Amit Joshi
Apr 4 at 12:49
Added some Python code (I think). I'd like to know why the downvote? It's a simple solution that works. No weird functions or other constructs required. I didn't think an explanation was necessary, as modulo counts as basic arithmetic. IMO every developer should know what it does or should have the ability to invest 10 seconds into typing "modulo" in to the all-knowing search engine whom I shall not name.
– SimonC
Apr 4 at 13:02
@EricDuminil That was the reason I only added the pseudo-code in the first place. My point was merely that a simple solution is to use the modulo operation. AFAIK it's available in all programming languages. I provided a basic structure which resembles how to use it.
– SimonC
Apr 5 at 7:19
@EricDuminil Added Python code.
– SimonC
Apr 10 at 12:03
add a comment |
A simple thing you could do is use the modulo operator:
if (myFloat % 1 == 0) // Number is an int
else // numer is not an int
EDIT: Python code
if myFloat % 1 == 0:
# myFloat is an integer.
else:
# myFloat is NOT an integer
A simple thing you could do is use the modulo operator:
if (myFloat % 1 == 0) // Number is an int
else // numer is not an int
EDIT: Python code
if myFloat % 1 == 0:
# myFloat is an integer.
else:
# myFloat is NOT an integer
edited Apr 10 at 12:03
answered Apr 4 at 11:11
SimonCSimonC
608724
608724
2
As he mentioned, this is simply a logic. Not a working code. This should be fine IMO.
– Amit Joshi
Apr 4 at 12:49
Added some Python code (I think). I'd like to know why the downvote? It's a simple solution that works. No weird functions or other constructs required. I didn't think an explanation was necessary, as modulo counts as basic arithmetic. IMO every developer should know what it does or should have the ability to invest 10 seconds into typing "modulo" in to the all-knowing search engine whom I shall not name.
– SimonC
Apr 4 at 13:02
@EricDuminil That was the reason I only added the pseudo-code in the first place. My point was merely that a simple solution is to use the modulo operation. AFAIK it's available in all programming languages. I provided a basic structure which resembles how to use it.
– SimonC
Apr 5 at 7:19
@EricDuminil Added Python code.
– SimonC
Apr 10 at 12:03
add a comment |
2
As he mentioned, this is simply a logic. Not a working code. This should be fine IMO.
– Amit Joshi
Apr 4 at 12:49
Added some Python code (I think). I'd like to know why the downvote? It's a simple solution that works. No weird functions or other constructs required. I didn't think an explanation was necessary, as modulo counts as basic arithmetic. IMO every developer should know what it does or should have the ability to invest 10 seconds into typing "modulo" in to the all-knowing search engine whom I shall not name.
– SimonC
Apr 4 at 13:02
@EricDuminil That was the reason I only added the pseudo-code in the first place. My point was merely that a simple solution is to use the modulo operation. AFAIK it's available in all programming languages. I provided a basic structure which resembles how to use it.
– SimonC
Apr 5 at 7:19
@EricDuminil Added Python code.
– SimonC
Apr 10 at 12:03
2
2
As he mentioned, this is simply a logic. Not a working code. This should be fine IMO.
– Amit Joshi
Apr 4 at 12:49
As he mentioned, this is simply a logic. Not a working code. This should be fine IMO.
– Amit Joshi
Apr 4 at 12:49
Added some Python code (I think). I'd like to know why the downvote? It's a simple solution that works. No weird functions or other constructs required. I didn't think an explanation was necessary, as modulo counts as basic arithmetic. IMO every developer should know what it does or should have the ability to invest 10 seconds into typing "modulo" in to the all-knowing search engine whom I shall not name.
– SimonC
Apr 4 at 13:02
Added some Python code (I think). I'd like to know why the downvote? It's a simple solution that works. No weird functions or other constructs required. I didn't think an explanation was necessary, as modulo counts as basic arithmetic. IMO every developer should know what it does or should have the ability to invest 10 seconds into typing "modulo" in to the all-knowing search engine whom I shall not name.
– SimonC
Apr 4 at 13:02
@EricDuminil That was the reason I only added the pseudo-code in the first place. My point was merely that a simple solution is to use the modulo operation. AFAIK it's available in all programming languages. I provided a basic structure which resembles how to use it.
– SimonC
Apr 5 at 7:19
@EricDuminil That was the reason I only added the pseudo-code in the first place. My point was merely that a simple solution is to use the modulo operation. AFAIK it's available in all programming languages. I provided a basic structure which resembles how to use it.
– SimonC
Apr 5 at 7:19
@EricDuminil Added Python code.
– SimonC
Apr 10 at 12:03
@EricDuminil Added Python code.
– SimonC
Apr 10 at 12:03
add a comment |
What I used to do in the past in C++ is, lets say you have these variables:
float x = 1.5;
float y = 1.0;
Then you could do something like this:
if(x == (int)x)
return 1;
else return 0;
This will return 0 because 1.5 is not equal to 1
if(y == (int)y)
return 1;
else return 0;
This will return 1 because 1.0 is equal to 1
Of course your question is about Python and the function is_integer() should work great, I just thought some people might find this useful.
1
The question was to convert a float to int whenever the float in question has an integer value. AFAIK this is not possible in C++, because you cannot return different values from a function.
– M.Herzkamp
Apr 4 at 11:49
3
@M.Herzkamp you could have aunionthough.
– Baldrickk
Apr 4 at 12:13
And also you could set another integer variable and save the float there if the condition above is met
– Stefan Kostoski
Apr 4 at 12:40
1
The digression on C++ isn't really relevant. You can do the same thing in Python:foo = lambda x: int(x) if int(x) == x else x. (Or in Python 3.8, to avoid the duplicate call toint,lambda x: y if (y:=int(x)) == x else x.
– chepner
Apr 4 at 13:11
1
filterdoesn't modify the values in the list; the function is just a predicate that decides whether or not to select the original value for its output. Usemapinstead.
– chepner
Apr 5 at 11:14
|
show 4 more comments
What I used to do in the past in C++ is, lets say you have these variables:
float x = 1.5;
float y = 1.0;
Then you could do something like this:
if(x == (int)x)
return 1;
else return 0;
This will return 0 because 1.5 is not equal to 1
if(y == (int)y)
return 1;
else return 0;
This will return 1 because 1.0 is equal to 1
Of course your question is about Python and the function is_integer() should work great, I just thought some people might find this useful.
1
The question was to convert a float to int whenever the float in question has an integer value. AFAIK this is not possible in C++, because you cannot return different values from a function.
– M.Herzkamp
Apr 4 at 11:49
3
@M.Herzkamp you could have aunionthough.
– Baldrickk
Apr 4 at 12:13
And also you could set another integer variable and save the float there if the condition above is met
– Stefan Kostoski
Apr 4 at 12:40
1
The digression on C++ isn't really relevant. You can do the same thing in Python:foo = lambda x: int(x) if int(x) == x else x. (Or in Python 3.8, to avoid the duplicate call toint,lambda x: y if (y:=int(x)) == x else x.
– chepner
Apr 4 at 13:11
1
filterdoesn't modify the values in the list; the function is just a predicate that decides whether or not to select the original value for its output. Usemapinstead.
– chepner
Apr 5 at 11:14
|
show 4 more comments
What I used to do in the past in C++ is, lets say you have these variables:
float x = 1.5;
float y = 1.0;
Then you could do something like this:
if(x == (int)x)
return 1;
else return 0;
This will return 0 because 1.5 is not equal to 1
if(y == (int)y)
return 1;
else return 0;
This will return 1 because 1.0 is equal to 1
Of course your question is about Python and the function is_integer() should work great, I just thought some people might find this useful.
What I used to do in the past in C++ is, lets say you have these variables:
float x = 1.5;
float y = 1.0;
Then you could do something like this:
if(x == (int)x)
return 1;
else return 0;
This will return 0 because 1.5 is not equal to 1
if(y == (int)y)
return 1;
else return 0;
This will return 1 because 1.0 is equal to 1
Of course your question is about Python and the function is_integer() should work great, I just thought some people might find this useful.
answered Apr 4 at 10:33
Stefan KostoskiStefan Kostoski
51
51
1
The question was to convert a float to int whenever the float in question has an integer value. AFAIK this is not possible in C++, because you cannot return different values from a function.
– M.Herzkamp
Apr 4 at 11:49
3
@M.Herzkamp you could have aunionthough.
– Baldrickk
Apr 4 at 12:13
And also you could set another integer variable and save the float there if the condition above is met
– Stefan Kostoski
Apr 4 at 12:40
1
The digression on C++ isn't really relevant. You can do the same thing in Python:foo = lambda x: int(x) if int(x) == x else x. (Or in Python 3.8, to avoid the duplicate call toint,lambda x: y if (y:=int(x)) == x else x.
– chepner
Apr 4 at 13:11
1
filterdoesn't modify the values in the list; the function is just a predicate that decides whether or not to select the original value for its output. Usemapinstead.
– chepner
Apr 5 at 11:14
|
show 4 more comments
1
The question was to convert a float to int whenever the float in question has an integer value. AFAIK this is not possible in C++, because you cannot return different values from a function.
– M.Herzkamp
Apr 4 at 11:49
3
@M.Herzkamp you could have aunionthough.
– Baldrickk
Apr 4 at 12:13
And also you could set another integer variable and save the float there if the condition above is met
– Stefan Kostoski
Apr 4 at 12:40
1
The digression on C++ isn't really relevant. You can do the same thing in Python:foo = lambda x: int(x) if int(x) == x else x. (Or in Python 3.8, to avoid the duplicate call toint,lambda x: y if (y:=int(x)) == x else x.
– chepner
Apr 4 at 13:11
1
filterdoesn't modify the values in the list; the function is just a predicate that decides whether or not to select the original value for its output. Usemapinstead.
– chepner
Apr 5 at 11:14
1
1
The question was to convert a float to int whenever the float in question has an integer value. AFAIK this is not possible in C++, because you cannot return different values from a function.
– M.Herzkamp
Apr 4 at 11:49
The question was to convert a float to int whenever the float in question has an integer value. AFAIK this is not possible in C++, because you cannot return different values from a function.
– M.Herzkamp
Apr 4 at 11:49
3
3
@M.Herzkamp you could have a
union though.– Baldrickk
Apr 4 at 12:13
@M.Herzkamp you could have a
union though.– Baldrickk
Apr 4 at 12:13
And also you could set another integer variable and save the float there if the condition above is met
– Stefan Kostoski
Apr 4 at 12:40
And also you could set another integer variable and save the float there if the condition above is met
– Stefan Kostoski
Apr 4 at 12:40
1
1
The digression on C++ isn't really relevant. You can do the same thing in Python:
foo = lambda x: int(x) if int(x) == x else x. (Or in Python 3.8, to avoid the duplicate call to int, lambda x: y if (y:=int(x)) == x else x.– chepner
Apr 4 at 13:11
The digression on C++ isn't really relevant. You can do the same thing in Python:
foo = lambda x: int(x) if int(x) == x else x. (Or in Python 3.8, to avoid the duplicate call to int, lambda x: y if (y:=int(x)) == x else x.– chepner
Apr 4 at 13:11
1
1
filter doesn't modify the values in the list; the function is just a predicate that decides whether or not to select the original value for its output. Use map instead.– chepner
Apr 5 at 11:14
filter doesn't modify the values in the list; the function is just a predicate that decides whether or not to select the original value for its output. Use map instead.– chepner
Apr 5 at 11:14
|
show 4 more comments
def your_function(i):
if i.is_integer():
return int(i)
else:
return float(i)
While this may answer the question, it would be very helpful if you could add on what is happening in there and how does it solve the problem, in order to increase the lifetime of your answer and to attract the users looking for the similar solution.
– DirtyBit
Apr 10 at 10:33
strings and floats have a function called is_integer, which returns true if it's a number, and false if anything else (including floats). So, if it's an int, return it as an int. Anything else (it's a float) and return it as a float.
– xcrafter_40
Apr 11 at 1:01
@ xcrafter_40 not as a comment, you may edit your answer to add the explanation. :)
– DirtyBit
Apr 11 at 6:30
add a comment |
def your_function(i):
if i.is_integer():
return int(i)
else:
return float(i)
While this may answer the question, it would be very helpful if you could add on what is happening in there and how does it solve the problem, in order to increase the lifetime of your answer and to attract the users looking for the similar solution.
– DirtyBit
Apr 10 at 10:33
strings and floats have a function called is_integer, which returns true if it's a number, and false if anything else (including floats). So, if it's an int, return it as an int. Anything else (it's a float) and return it as a float.
– xcrafter_40
Apr 11 at 1:01
@ xcrafter_40 not as a comment, you may edit your answer to add the explanation. :)
– DirtyBit
Apr 11 at 6:30
add a comment |
def your_function(i):
if i.is_integer():
return int(i)
else:
return float(i)
def your_function(i):
if i.is_integer():
return int(i)
else:
return float(i)
answered Apr 9 at 4:22
xcrafter_40xcrafter_40
368
368
While this may answer the question, it would be very helpful if you could add on what is happening in there and how does it solve the problem, in order to increase the lifetime of your answer and to attract the users looking for the similar solution.
– DirtyBit
Apr 10 at 10:33
strings and floats have a function called is_integer, which returns true if it's a number, and false if anything else (including floats). So, if it's an int, return it as an int. Anything else (it's a float) and return it as a float.
– xcrafter_40
Apr 11 at 1:01
@ xcrafter_40 not as a comment, you may edit your answer to add the explanation. :)
– DirtyBit
Apr 11 at 6:30
add a comment |
While this may answer the question, it would be very helpful if you could add on what is happening in there and how does it solve the problem, in order to increase the lifetime of your answer and to attract the users looking for the similar solution.
– DirtyBit
Apr 10 at 10:33
strings and floats have a function called is_integer, which returns true if it's a number, and false if anything else (including floats). So, if it's an int, return it as an int. Anything else (it's a float) and return it as a float.
– xcrafter_40
Apr 11 at 1:01
@ xcrafter_40 not as a comment, you may edit your answer to add the explanation. :)
– DirtyBit
Apr 11 at 6:30
While this may answer the question, it would be very helpful if you could add on what is happening in there and how does it solve the problem, in order to increase the lifetime of your answer and to attract the users looking for the similar solution.
– DirtyBit
Apr 10 at 10:33
While this may answer the question, it would be very helpful if you could add on what is happening in there and how does it solve the problem, in order to increase the lifetime of your answer and to attract the users looking for the similar solution.
– DirtyBit
Apr 10 at 10:33
strings and floats have a function called is_integer, which returns true if it's a number, and false if anything else (including floats). So, if it's an int, return it as an int. Anything else (it's a float) and return it as a float.
– xcrafter_40
Apr 11 at 1:01
strings and floats have a function called is_integer, which returns true if it's a number, and false if anything else (including floats). So, if it's an int, return it as an int. Anything else (it's a float) and return it as a float.
– xcrafter_40
Apr 11 at 1:01
@ xcrafter_40 not as a comment, you may edit your answer to add the explanation. :)
– DirtyBit
Apr 11 at 6:30
@ xcrafter_40 not as a comment, you may edit your answer to add the explanation. :)
– DirtyBit
Apr 11 at 6:30
add a comment |
The answer to the question as it is put requires comparison of the float value. One must always avoid equality operations on floats. Some form of rounding is a valid approach.
But for this kind of use case, the decimals module is your friend. Decimals have the advantage of absolute accuracy for the values cited in the question compared to floats and also achieve completely reliable results in comparison operations.
add a comment |
The answer to the question as it is put requires comparison of the float value. One must always avoid equality operations on floats. Some form of rounding is a valid approach.
But for this kind of use case, the decimals module is your friend. Decimals have the advantage of absolute accuracy for the values cited in the question compared to floats and also achieve completely reliable results in comparison operations.
add a comment |
The answer to the question as it is put requires comparison of the float value. One must always avoid equality operations on floats. Some form of rounding is a valid approach.
But for this kind of use case, the decimals module is your friend. Decimals have the advantage of absolute accuracy for the values cited in the question compared to floats and also achieve completely reliable results in comparison operations.
The answer to the question as it is put requires comparison of the float value. One must always avoid equality operations on floats. Some form of rounding is a valid approach.
But for this kind of use case, the decimals module is your friend. Decimals have the advantage of absolute accuracy for the values cited in the question compared to floats and also achieve completely reliable results in comparison operations.
edited Apr 10 at 21:47
answered Apr 10 at 21:39
hi2meukhi2meuk
173
173
add a comment |
add a comment |
divmod alternative:
def f(x):
return x if divmod(x, 1)[1] else int(x)
add a comment |
divmod alternative:
def f(x):
return x if divmod(x, 1)[1] else int(x)
add a comment |
divmod alternative:
def f(x):
return x if divmod(x, 1)[1] else int(x)
divmod alternative:
def f(x):
return x if divmod(x, 1)[1] else int(x)
answered Apr 12 at 8:04
sardoksardok
7181614
7181614
add a comment |
add a comment |
if you looking for direct approach without using .is_integer() method?
is_integer is a method for float you can check using,
dir(float) #eg dir(1.0)
will list of methods available for float including .is_integer()
Now come to the point...
Direct Approach:
int(float_num) -> will return int so do direct comparison
syntax: int(num) == num -> int(num) otherwise -> num
script: n = int(num) if int(num) == num else num
eg:
num = 1.5
n = int(num) if int(num) == num else num
print n
>>> 1.5
As a function,
>>> def num_con(n):
... return int(n) if int(n) == n else n
Sample Input/output:
>>> num_con(1.0)
1
>>> num_con(1.5)
1.5
>>> num_con(2.5)
2.5
>>> num_con(2.0)
2
>>>
same way for list of numbers,
a) single line:
[int(i) if int(i) == i else i for i in [1.5,2.0,3.2,4.0,5.5]]
b) function reuse:
[num_con(i) for i in [1.5,2.0,3.2,4.0,5.5]] #num_con is a function which we wrote on top
add a comment |
if you looking for direct approach without using .is_integer() method?
is_integer is a method for float you can check using,
dir(float) #eg dir(1.0)
will list of methods available for float including .is_integer()
Now come to the point...
Direct Approach:
int(float_num) -> will return int so do direct comparison
syntax: int(num) == num -> int(num) otherwise -> num
script: n = int(num) if int(num) == num else num
eg:
num = 1.5
n = int(num) if int(num) == num else num
print n
>>> 1.5
As a function,
>>> def num_con(n):
... return int(n) if int(n) == n else n
Sample Input/output:
>>> num_con(1.0)
1
>>> num_con(1.5)
1.5
>>> num_con(2.5)
2.5
>>> num_con(2.0)
2
>>>
same way for list of numbers,
a) single line:
[int(i) if int(i) == i else i for i in [1.5,2.0,3.2,4.0,5.5]]
b) function reuse:
[num_con(i) for i in [1.5,2.0,3.2,4.0,5.5]] #num_con is a function which we wrote on top
add a comment |
if you looking for direct approach without using .is_integer() method?
is_integer is a method for float you can check using,
dir(float) #eg dir(1.0)
will list of methods available for float including .is_integer()
Now come to the point...
Direct Approach:
int(float_num) -> will return int so do direct comparison
syntax: int(num) == num -> int(num) otherwise -> num
script: n = int(num) if int(num) == num else num
eg:
num = 1.5
n = int(num) if int(num) == num else num
print n
>>> 1.5
As a function,
>>> def num_con(n):
... return int(n) if int(n) == n else n
Sample Input/output:
>>> num_con(1.0)
1
>>> num_con(1.5)
1.5
>>> num_con(2.5)
2.5
>>> num_con(2.0)
2
>>>
same way for list of numbers,
a) single line:
[int(i) if int(i) == i else i for i in [1.5,2.0,3.2,4.0,5.5]]
b) function reuse:
[num_con(i) for i in [1.5,2.0,3.2,4.0,5.5]] #num_con is a function which we wrote on top
if you looking for direct approach without using .is_integer() method?
is_integer is a method for float you can check using,
dir(float) #eg dir(1.0)
will list of methods available for float including .is_integer()
Now come to the point...
Direct Approach:
int(float_num) -> will return int so do direct comparison
syntax: int(num) == num -> int(num) otherwise -> num
script: n = int(num) if int(num) == num else num
eg:
num = 1.5
n = int(num) if int(num) == num else num
print n
>>> 1.5
As a function,
>>> def num_con(n):
... return int(n) if int(n) == n else n
Sample Input/output:
>>> num_con(1.0)
1
>>> num_con(1.5)
1.5
>>> num_con(2.5)
2.5
>>> num_con(2.0)
2
>>>
same way for list of numbers,
a) single line:
[int(i) if int(i) == i else i for i in [1.5,2.0,3.2,4.0,5.5]]
b) function reuse:
[num_con(i) for i in [1.5,2.0,3.2,4.0,5.5]] #num_con is a function which we wrote on top
answered Apr 10 at 13:26
Mohideen ibn MohammedMohideen ibn Mohammed
7,75835164
7,75835164
add a comment |
add a comment |
4
one way could be to check the float using
is_integer()if that passes, convert it toint?– DirtyBit
Apr 4 at 7:47
7
Floats are approximations,
1.0could actually be1.00000000000001or0.999999999999.– Barmar
Apr 4 at 7:49
6
Note that because of duck typing, this passage you want to achieve is probably out of place or useless, depending on context.
– Federico S
Apr 4 at 7:52
13
Please specify your exact requirements in words/rules rather than just with a single example!
– Lightness Races in Orbit
Apr 4 at 10:35
5
def f(x): if x == 1.0: return 1 else return 1.5– Bakuriu
Apr 4 at 20:26