Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I try to find a way to check if number contains "2" "3" "4" "5";
So 1234 meaning is "false" and 0110 meaning is true.
I try convert float to string and check with .find() but it's too long and i can't convert properly.
a = Decimal(1) / Decimal(123456789)
print a
8.100000073710000670761006104E-9
a = str(a)
print a
8.100000073710000670761006104E-9
So please help me (:
edit:
I have a calculation formula and want to refine results. so i can use result as an input and calculate original number.
it's some kind of encription algoritm and need special number set.
for example
9,9989001209866914639389667136615e-8
is in my set cause
1 / 9,9989001209866914639389667136615e-8 = 10001100
1 / 10001100 = 9,9989001209866914639389667136615e-8
also, number source has been generated seperately. i try to read source and refine only accepted numbers.
To divide these numbers and getting rid of scientific notation, I used the following code:
from decimal import *
a = '{0:f}'.format(Decimal(1)/Decimal(123456789))
print a.find('1234')
print a.find('810')
I am not sure of the conditions of your search in the string. But I hope that would be helpful.
I don't understand your initial problem description. If you meant whether the reciprocal of a number contains those digits, one issue is that the majority of such results have an infinite number of digits. Writing a number like 0110 complicates matters further because that's octal in Python 2 (invalid in Python 3); its value is 72.
But one thing I can easily adress, the "too long" part. You can request arbitrary (but still finite) precision from Decimal:
>>> f='{:f}'.format(decimal.Context(prec=200).divide(1,1234))
>>> f[:40]
'0.00081037277147487844408427876823338735'
>>> f.index('00810372')
3
>>> f.index('00810372', 3+1)
91
So as it happens, the digit stream of 1/1234 repeats after 88 decimal digits. All rationals have some such loop length (1/123456789 loops after 6855006 digits). But the default Decimal context didn't produce enough digits to observe the entire loop for this number.
A proper solution to this challenge would probably involve performing the long division explicitly, and tracking the fractions encountered along the way. Then you can easily detect when you find a repetition. Something along the lines of (probably slow):
fractions=set()
digits=[]
while fraction not in fractions:
digit = math.floor(fraction)
fractions.add(fraction)
digits.append(digit)
fraction = (fraction-digit)*10
If I understand your problem well, you could try using regular expressions. Here's an interactive way to play around with regular expressions given your problem: https://regex101.com/r/i2mZmK/2/
And a potential solution in python:
import re
from decimal import *
regex = re.compile(r"(2|3|4|5)")
a = Decimal(1) / Decimal(123456789)
def check_number():
result = regex.search(str(a))
if result is None:
check = True
else:
check = False
return check
print(check_number())
def returnsomething():
demo_number = 345.43565
list = [2, 3, 4]
for number in list:
if str(number) in str(demo_number):
return True
return False
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am working on a program that outputs the condition number of a big matrix, so I used the Power Method to get the Largest EigenValue, but the values are large numbers (float) larger than 1*10^310, and in the end the values become "Infinity", I tried the decimal module but it's the same. How can I store those large float values? Or maybe another method that uses shorter values?
(I'm not allowed to use any module that helps explicitly the proccess as Numpy)
You want to use the decimal module:
from decimal import Decimal
x = Decimal('1.345e1310')
y = Decimal('1.0e1310')
print(x + y)
Result:
2.345E+1310
Don't work with floating point values if you can help it; they are very difficult to reason about and will bite you!
Whenever you are trying to work with floats, especially ones with lots of digits, you should consider how you can shift it into an integer range and if you have invalid or needless accuracy beyond the floating part of your value
perhaps into a bigger int such as 10**400 or 10**100000, which should provide plenty of room for your floating point digits, while allowing you to work in the integer space
directly convert or scale down, discarding digits beyond the decimal point (consider how accurate the measurement really is)
>>> int(1.0 * 10) * 10**999 # divide off 10**690 later or note in units
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>> int(1.0 * 10**10) # multiply by 10**300 later or note in units
10000000000
Practically, this is why you would want scientific notation - don't store the data with all its digits if you don't need them, keep the smallest amount you need and a second multiplier for the size factor (scientific notation does use a floating-point, but the idea is the same for integers)
Then, rather than working with floating points, you can recall the multiplier(s) at the end when you're done with your math (even multiplying them out separately)
It may even be sufficient to remove a significant portion of the digits entirely in some regular manner, and display the factor in the post-calculation units for whom or whatever is consuming the data
While this question is about large numbers, even decimal.Decimal unfortunately does not handle the small bits of floating points the way one might expect, as they're subject to some aliasing from how they're stored
https://en.wikipedia.org/wiki/Floating-point_arithmetic#IEEE_754:_floating_point_in_modern_computers
This is problematic with normal python floats, and so extends to Decimals, even of a size you may expect to see in normal use!
>>> 9007199254740993.0
9007199254740992.0
>>> Decimal(9007199254740993.0) # NOTE converted to float before Decimal
Decimal('9007199254740992')
Adapted from Which is the first integer that an IEEE 754 float is incapable of representing exactly?
Example to the original question
>>> a = Decimal(10**310) * Decimal(1.0)
>>> b = Decimal(1)
>>> a + b - a
Decimal('0E+283')
Further examples
>>> a = Decimal(10**310)
>>> b = Decimal(0.1)
>>> a + b - a
Decimal('0')
>>> a
Decimal('10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')
>>> b
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> 10**-100
1e-100
>>> Decimal(10**-100)
Decimal('1.00000000000000001999189980260288361964776078853415942018260300593659569925554346761767628861329298958274607481091185079852827053974965402226843604196126360835628314127871794272492894246908066589163059300043457860230145025079449986855914338755579873208034769049845635890960693359375E-100')
>>> 10**-1000
0.0
>>> Decimal(10**-1000)
Decimal('0')
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am working on a program that outputs the condition number of a big matrix, so I used the Power Method to get the Largest EigenValue, but the values are large numbers (float) larger than 1*10^310, and in the end the values become "Infinity", I tried the decimal module but it's the same. How can I store those large float values? Or maybe another method that uses shorter values?
(I'm not allowed to use any module that helps explicitly the proccess as Numpy)
You want to use the decimal module:
from decimal import Decimal
x = Decimal('1.345e1310')
y = Decimal('1.0e1310')
print(x + y)
Result:
2.345E+1310
Don't work with floating point values if you can help it; they are very difficult to reason about and will bite you!
Whenever you are trying to work with floats, especially ones with lots of digits, you should consider how you can shift it into an integer range and if you have invalid or needless accuracy beyond the floating part of your value
perhaps into a bigger int such as 10**400 or 10**100000, which should provide plenty of room for your floating point digits, while allowing you to work in the integer space
directly convert or scale down, discarding digits beyond the decimal point (consider how accurate the measurement really is)
>>> int(1.0 * 10) * 10**999 # divide off 10**690 later or note in units
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>> int(1.0 * 10**10) # multiply by 10**300 later or note in units
10000000000
Practically, this is why you would want scientific notation - don't store the data with all its digits if you don't need them, keep the smallest amount you need and a second multiplier for the size factor (scientific notation does use a floating-point, but the idea is the same for integers)
Then, rather than working with floating points, you can recall the multiplier(s) at the end when you're done with your math (even multiplying them out separately)
It may even be sufficient to remove a significant portion of the digits entirely in some regular manner, and display the factor in the post-calculation units for whom or whatever is consuming the data
While this question is about large numbers, even decimal.Decimal unfortunately does not handle the small bits of floating points the way one might expect, as they're subject to some aliasing from how they're stored
https://en.wikipedia.org/wiki/Floating-point_arithmetic#IEEE_754:_floating_point_in_modern_computers
This is problematic with normal python floats, and so extends to Decimals, even of a size you may expect to see in normal use!
>>> 9007199254740993.0
9007199254740992.0
>>> Decimal(9007199254740993.0) # NOTE converted to float before Decimal
Decimal('9007199254740992')
Adapted from Which is the first integer that an IEEE 754 float is incapable of representing exactly?
Example to the original question
>>> a = Decimal(10**310) * Decimal(1.0)
>>> b = Decimal(1)
>>> a + b - a
Decimal('0E+283')
Further examples
>>> a = Decimal(10**310)
>>> b = Decimal(0.1)
>>> a + b - a
Decimal('0')
>>> a
Decimal('10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')
>>> b
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> 10**-100
1e-100
>>> Decimal(10**-100)
Decimal('1.00000000000000001999189980260288361964776078853415942018260300593659569925554346761767628861329298958274607481091185079852827053974965402226843604196126360835628314127871794272492894246908066589163059300043457860230145025079449986855914338755579873208034769049845635890960693359375E-100')
>>> 10**-1000
0.0
>>> Decimal(10**-1000)
Decimal('0')
I have a bunch of floating point numbers that are either x.0 or x.5 and if they are x.0 I want no decimal points displayed, and if they are x.5 I want one decimal point displayed.
I have come up with a one-liner that does the job:
f'{x:+.{int(bool(x % 1))}f}'
Where int(bool(x % 1)) will always be 0 or 1 depending on whether modulo yields a remainder.
This works fine because of the nature of my float inputs, but it got me thinking, what if my inputs weren't so neat? For example the above one-liner with 10.01 as an input returns 10.0. My temptation is to first round the float to the desired precision:
f'{x:+.{int(bool(round(x, 1) % 1))}f}'
If there wasn't already a lot going on inside the f-string in my first example, there is now.
To be clear about my question:
Firstly, is my first method the 'right' way to go about what I'm actually trying to achieve given my real-world inputs?
Secondly, how about in the case of the hypothetical problem and my second example?
Thirdly, I'd like to canvas opinion from the community regarding where use of f-string crosses the line to abuse. As an example of how one might be tempted to pack a lot of stuff into the f-string, how about something like this to get a list of strings containing numbers to sort alphabetically:
f"String with number:{' ' if x >= 1000 else ' ' if x >= 100 else ' ' if x >= 10 else ' '}{x:+.{int(bool(round(x, 1) % 1))}f}"
So I hope tying this question about overuse of f-string in with my rounding question doesn't cause the overall question to be too vague, but these are two issues that I'm considering together. I suppose the 'neatness' of f-string can provide a temptation to shoehorn everything into one-liners.
While doing this exercise:
>>> amount = 24.325
>>> print("%7f" % amount)
>>> 24.325000
I didn't understand why instead of printing ' 24.325' (whith 1 space before the number) it just added three '0' and didn't move it towards the right at all.
So I thought that maybe, when you don't specify the precision, Python adds '0' until the number has at least 6 digits after the decimal point (if it doesn't already have them) and THAN takes in consideration the width I set (in this case, 7) and adds the needed spaces. In the exercise, with the extra '0's, it ends up having 9 digits, so it didn't add any. Is my hypothesis correct?
The question is, why 6 digits after the decimal point? Is it something that Python does by default?
Thank you.
The python docs exactly describe how the formatting operator % works.
In particular, you can have a minimum field with an a precision.
The former defines the minimum length of your resulting string, the latter gives the number of digits after the decimal point.
As the default precision is 6 for %f, you get what you get.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm taking an introductory Python course and we have an assignment that asks us to simulate the way the floating point numbers are stored.
Basically, we have to demonstrate 5 digits of Mantissa. For example, you input 123 and it must come out as 12300. If you input 12345678 it must come out as 12345. How can this be done? Is there a function for that or is it just a formmating issue? Keep in mind, this is an introductory course and we're not allowed to use any external libraries.
You can use Python's string formatting functionality:
'{:<05d}'.format(number)[:5]
Some examples:
>>> '{:<05d}'.format(123)[:5]
'12300'
>>> '{:<05d}'.format(12345678)[:5]
'12345'
Some clarification:
< says: align the number on the left.
0 says: use 0 as padding character.
5 says: set the width to at least five.
d says: it's a decimal.
As the number can be longer than five digits we take only the first five characters by doing [:5]. This is called slice notation and it allows you to take a slice of a string.
So, let's try taking the problem, and writing the rough framework of what we have to do. Notice that whenever I run into a problem that isn't immediately obvious, I push it into its own function, which I can deal with later:
string = str(number)
if len(string) > 5:
string = truncate_string(string)
elif len(string) < 5:
string = pad_string_with_zeros(string)
So, let's try implementing truncate_string and pad_string_with_zeros.
A string is basically a list of characters. How would we get the first 5 elements of a list? Through list slicing. Therefore, we can implement truncate_string like so:
def truncate_string(string):
return string[:5]
How do we pad strings with zeros? Well, if you consult the Python documentation, you could use the ljust function:
>>> '11'.ljust(5, '0')
'11000'
>>> '12345678'.ljust(5, '0')
'12345'
Therefore, our function could be:
def pad_string_with_zeros(string):
return string.ljust(5, '0')
Alternatively, we could have used a while loop:
def pad_string_with_zeros(string):
while len(string) < 5:
string += '0'
...although that'll be more inefficient.
If we move all our functions into the main code, then we might get something like this:
string = str(number)
if len(string) > 5:
string = string[:5]
elif len(string) < 5:
string = string.ljust(5, '0')
As it turns out, list slicing will not throw errors, even if you pass in too small or too large strings. For example, '12'[:5] will result in the string '12'.
Therefore, we don't need to even check for the size of the string, and can compact it down to the following lines:
string = str(number)
string = string[:5].ljust(5, '0')