using list operator "in" with floating point values - python

I have a list with floats, each number with 3 decimals (eg. 474.259). If I verify the number in the list like this:
if 474.259 in list_sample:
print "something!"
Then the message is shown, but if I take the number from another list and I round it:
number = other_list[10]
number = round(number, 3)
if number == 474.259:
print "the numbers are same!"
if number in list_sample:
print "something!"
The second message is not shown.

Comparing floating point numbers for exact equality usually won't do what you want. This is because floating point numbers in computers have a representation (storage format) which is inherently inaccurate for many real numbers.
I suggest reading about it here: http://floating-point-gui.de/ and doing something like a "fuzzy compare" using an "epsilon" tolerance value to consider the numbers equal so long as they differ by less than x% or whatever.

You could also following an approach, where you compare the values based on an arbitrary precision.
For example, convert all your floats like this:
def internalPrecision(number):
precision = 1000
return int(round(number * precision))
If you do this, both operators == and in should work.

You can use numpy.isclose() instead of Python's in.
import numpy as np
other_list = np.array([474.251001, 123.456])
number = other_list[0]
number = round(number, 3)
if number == 474.251:
print "number == 474.251"
if number in other_list:
print "number in other_list"
if any(np.isclose(number, other_list, rtol=1e-7)):
print 'any(np.isclose(number, other_list, rtol=1e-7))'
Output:
number == 474.251
any(np.isclose(number, other_list, rtol=1e-7))

Related

How can I check the length of a long float? Python is truncating the length [duplicate]

I have some number 0.0000002345E^-60. I want to print the floating point value as it is.
What is the way to do it?
print %f truncates it to 6 digits. Also %n.nf gives fixed numbers. What is the way to print without truncation.
Like this?
>>> print('{:.100f}'.format(0.0000002345E-60))
0.0000000000000000000000000000000000000000000000000000000000000000002344999999999999860343602938602754
As you might notice from the output, it’s not really that clear how you want to do it. Due to the float representation you lose precision and can’t really represent the number precisely. As such it’s not really clear where you want the number to stop displaying.
Also note that the exponential representation is often used to more explicitly show the number of significant digits the number has.
You could also use decimal to not lose the precision due to binary float truncation:
>>> from decimal import Decimal
>>> d = Decimal('0.0000002345E-60')
>>> p = abs(d.as_tuple().exponent)
>>> print(('{:.%df}' % p).format(d))
0.0000000000000000000000000000000000000000000000000000000000000000002345
You can use decimal.Decimal:
>>> from decimal import Decimal
>>> str(Decimal(0.0000002345e-60))
'2.344999999999999860343602938602754401109865640550232148836753621775217856801120686600683401464097113374472942165409862789978024748827516129306833728589548440037314681709534891496105046826414763927459716796875E-67'
This is the actual value of float created by literal 0.0000002345e-60. Its value is a number representable as python float which is closest to actual 0.0000002345 * 10**-60.
float should be generally used for approximate calculations. If you want accurate results you should use something else, like mentioned Decimal.
If I understand, you want to print a float?
The problem is, you cannot print a float.
You can only print a string representation of a float. So, in short, you cannot print a float, that is your answer.
If you accept that you need to print a string representation of a float, and your question is how specify your preferred format for the string representations of your floats, then judging by the comments you have been very unclear in your question.
If you would like to print the string representations of your floats in exponent notation, then the format specification language allows this:
{:g} or {:G}, depending whether or not you want the E in the output to be capitalized). This gets around the default precision for e and E types, which leads to unwanted trailing 0s in the part before the exponent symbol.
Assuming your value is my_float, "{:G}".format(my_float) would print the output the way that the Python interpreter prints it. You could probably just print the number without any formatting and get the same exact result.
If your goal is to print the string representation of the float with its current precision, in non-exponentiated form, User poke describes a good way to do this by casting the float to a Decimal object.
If, for some reason, you do not want to do this, you can do something like is mentioned in this answer. However, you should set 'max_digits' to sys.float_info.max_10_exp, instead of 14 used in the answer. This requires you to import sys at some point prior in the code.
A full example of this would be:
import math
import sys
def precision_and_scale(x):
max_digits = sys.float_info.max_10_exp
int_part = int(abs(x))
magnitude = 1 if int_part == 0 else int(math.log10(int_part)) + 1
if magnitude >= max_digits:
return (magnitude, 0)
frac_part = abs(x) - int_part
multiplier = 10 ** (max_digits - magnitude)
frac_digits = multiplier + int(multiplier * frac_part + 0.5)
while frac_digits % 10 == 0:
frac_digits /= 10
scale = int(math.log10(frac_digits))
return (magnitude + scale, scale)
f = 0.0000002345E^-60
p, s = precision_and_scale(f)
print "{:.{p}f}".format(f, p=p)
But I think the method involving casting to Decimal is probably better, overall.

Python round to nearest .0125

Does anyone know how to round a number to nearest .0125? For example there's a number 167.1131 then it needs to be converted to 167.1125. I have tried to do it with round but it rounds to 0.x.
Convert it to "0.0125's", round THAT, and convert back:
round(x/0.0125)*0.0125
The round() function is focused on rounding to tenths, hundredths, thousandths and so on - essentially rounding to some negative exponent of 10.
So, as 0.0125 is not such a number that the round() can handle, you can
either apply a multiplication to your input number before giving it to round, so that it can do a rounding for which it is designed, and afterwards you correct for the initial multiplication. One of the other answers does it like this.
or you can, if you think the first approach looks complicated, solve the problem with pure mathematics. The code below essentially looks how much there is actually "too much" above a multiple of 0.0125. This "too much" amount is a remainder (modulus) of a division. This division is done on integers, so there is an initial multiplication and correction afterwards, just like in the first approach.
Code for the second approach:
def round_0125(number):
mult_number = number * 10000
remainder = mult_number % 125
return (mult_number - remainder) / 10000
round_0125(167.1131)
#167.1125
round_0125(167.5738)
#167.5625
value = 167.1125
dec_value = value % 1 # get decimal part
whole_value = value // 1
my_range = np.arange(0, 1, 0.0125)
distance = np.abs(dec_value - my_range) # get the absolute distance
index = np.argmin(distance) # find the index of smallest distance
result = whole_value + my_range[index]

Displaying float values in python

Can anyone help with float values in python.
I want to access values from CPP.From cpp I am getting value say 20.251.
But in python its displaying as20.25099876 sometng like this.
I want to display value as it is coming frm cpp.
Thanks .
I have tried
i = c_ float
GetVal(Voltage, byref(i))
Print("Value is: " i.value)
Here you go
a = 20.25099876
result = format(a, '.3f')
print result
Decimals and floats are different in the sense that decimals have a base of ten (0-9) whereas float have a base of two (0,1). There are two approaches to rounding (not truncating the floating point, which just cuts the number off at the indicated decimal).
x = 20.25099876
s = format(x, '.2f')
print(s)
The .2 indicates the number of numbers post-float to print
rounding notation can be placed after a colon & inside braces of format strings
x = 20.25099876
'rounded : {:.2f}'.format(x)
One way to print the number without rounding is
num=20.25099876
num = num - (num % 0.0001)
print num
It will print 20.2509
If you want to print the value as it is , like a=20.25099876
Make it string. str(a) and print it.
Use "c_double" instead of "c_float" to get exact values from cpp.

How do I expand a long number (ending in e+##) to show in expanded form?

So, this may be a simple question but I'm having some trouble finding the answer anywhere.
Take for example I have a simple program where I want to divide a by b like so:
def main():
a = 12345678900000000
b = 1.25
answer = (a / b)
print(answer)
main()
This particular example would result in 9.87654312e+15. How do I get Python to ignore simplifying my number and just give me the whole number?
Thanks in advance, sorry if it's really basic, I wouldn't have asked if I could have found it through Google.
You are seeing the default str() conversion for floating point numbers at work. You can pick a different conversion by formatting the number explicitly.
The format() function can do this for you:
>>> n = 9.87654312e+15
>>> format(n, 'f')
'9876543120000000.000000'
See the Format Specification Mini-Language documentation for more options. The 'f' format is but one of several:
Fixed point. Displays the number as a fixed-point number. The default precision is 6.
The default precision resulting in the .000000 six digits after the decimal point; you can alter this by using .<precision>f instead:
>>> format(n, '.1f')
'9876543120000000.0'
but take into account that decimals are rounded to fit the requested precision.
The g format switches between using exponents (e) and f notation, depending on the size of the number, but won't include decimals if the number is whole; you could use a very large precision with 'g' to avoid printing decimals altogether:
>>> format(n, '.53g')
'9876543120000000'
To be explicit, str(n) is the same as format(n, '.12g'), repr(n) is format(n, '.17g'); both can use the exponent format when the exponent is larger than the precision.
just be more specific about the floating point format
>>> print answer
9.87654312e+15
>>> print "%.20f" % answer
9876543120000000.00000000000000000000

How to return a decimal after using int() function on a string?

Very basic question. If I set products as 3 and parcels as 2, I get 1. How do I have the last line print 1.5, a decimal, instead of simply 1?
products = raw_input('products shipped? ')
parcels = raw_input('parcels shipped? ')
print "Average Number of products per parcel"
print int(products) / int(parcels)
print float(products) / float(parcels)
If you want real numbers, use float, which represents real numbers. Don't use integers.
In Python 3 you'll get this automatically.
In Python 2 you can do from __future__ import division, then dividing two integers will result in a floating point number.
In either case you can use // instead of / if you decide you really needed an integer result instead. That works in Python 2 even if you don't do the import.
You can also convert either or both of the numbers to float to force a floating point result.
If you want the full decimal value use the below,
from decimal import Decimal
print Decimal(products) / Decimal(parcels)

Categories

Resources