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 4 months ago.
Improve this question
I write science-related codes with Python and I was wondering how the choice of units may affect my results.
For example, if I enter a distance as 1e-9 meters or 1 nm or 10 Angstroms, I would obtain the exact same result on paper. However, I know that the representation of these quantities is different on a computer. Therefore, I would like to know how important it is to choose the relevant set of units in scientific computing to maximize numerical precision.
How does the choice of units impact numerical precision?
I suggest you get as first step clarity what 'numerical precision' actually means with the side-effect of accepting the statement It doesn't affect it at all provided by Tim Roberts in the comments as short, clear and simple answer.
Usually you choose numerical precision yourself in your code by choice of the data types storing values and the way you perform calculations on these values.
The choice of units is just a choice of units and choice of data types for numerical representation of values in this units is another story.
In other words you have to know first what you actually want to do and how to achieve the results you expect.
Let's for example consider following code:
x = 1.0
dx = 0.000_000_000_000_000_1
steps = 1_000_000
for i in range(steps):
x += dx
print(x)
x = 1.0
x += sum([dx]*steps)
print(x)
x = 1.0
x += dx*steps
print(x)
printing:
1.0
1.0000000001
1.0000000001
as evidence that the choice of the way of performing calculations is the main issue when you experience surprising results and not the numerical precision or choice of units as such.
Related
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 24 days ago.
Improve this question
I'm stuck on a beginner level coding problem. Goal is to round a float number and output an integer. So x = 3.14159, output 3 (not 3.0). We're supposed to be able to do this using only what we've learned, and what we've learned is only 3 functions: .find, <string>[:], and converting the given x = float num into a string, via str().
How should I be thinking about this? When I write out what logically needs to happen, I always find myself needing if().
I ended up getting partial credit with the following code:
given: x = 3.14159
x = int(round(x))
print x
But I would like to solve it without int() or round(), or if(). My first thought was to use x[2:3] and x[3:4] to check the tenths and hundredths place values, but to proceed I still run into the if() wall.
This is a poorly constructed string manipulation problem because you'd never actually go about solving this problem this way. But using only what you've been taught, you can accomplish the task:
x = 3.14159
# 0.5 (optional?) add 0.5 to x so that it will be properly rounded
# when removing the digits after the decimal
x += 0.5
# 1. convert the int to a string
x_str = str(x)
# 2. find the index of the decimal point in the string
decimal_idx = x_str.find('.')
# 3. slice the string from the beginning to the decimal
x_int_str = x_str[:decimal_idx]
# 4. do something with the value
print(x_int_str)
You should use the built in string format feature:
x = 123.35643
rounded = f'{x:.2f}'
print(rounded)
Your output would be: 123.36
Or to get the whole number:
rounded = f'{x:.0f}'
print(rounded)
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 last year.
Improve this question
I know the floating point issues and I've read some documentations and have some understanding on Decimal type.
For example: .1 + .1 + .1 != .3 .
But why:
>>> 0.123456789 == 12.3456789 / 100
True
is True ? I expected False.
Because adding is inaccurate so I think division should also be inaccurate?
Not really an answer, but too long for the comments:
To explore this phenomenon, I wrote a simple program:
import random
def f(a,b,n):
x = random.uniform(a,b)
y = n*x
return x,y,x == y/n
Then for example
trials = [f(0,100,100) for _ in range(10000)]
print(len([x for x,y,t in trials if t])/10000)
prints values like 0.8634
I have tried a number of values for a,b,n, with == holding typically in the range 80% to 90%. A strange observation which confuses me:
f(0,100,100000000)
is much more likely to give rise to a counterexample than either
f(0,100,10000000)
or
f(0,100,10000000000)
I would have thought that for a,b fixed, the probability of x==y is monotonic in n, but it apparently isn't.
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
Question:
Given an array of floats (size N < 100), find the subset (size M = 10) whose sum is maximal but less than value K.
Example (using ints for simplicity)
INPUT:
array = [1,2,3,4,5,6,7,8,9,10,11,12,13]
K = 60
OUTPUT:
subset = [1,2,3,4,5,6,7,8,10,13] # sum of 59
I've tried searching on G4G, but I haven't found anything that accounts for the subset size of M = 10. I'm trying to solve this with Python 3, but any references or sources would be much appreciated.
A good starting point would be to read up on the 0-1 knapsack problem: Given a set of items with corresponding values and weights, and a maximum weight allowance W, find the set of items of maximum value which is within the weight allowance W.
Your problem is the same as this problem, but with all the item values = their weights - so you can just use a solution to the knapsack problem, or maybe (probably) you can make something a bit more time-efficient exploiting this.
Good luck!
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 7 years ago.
Improve this question
I'm doing Bayesian inference (manually, using a grid search) in Python. I want to calculate the probability of each model given the data. The problem is I can only calculate the 'evidence' in log, otherwise its 0.
So, even though its between 0-1, I can't get the results for:
Pr(data|model1) / (Pr(data|model1) + Pr(data|model2))
Since each term is 0 in its non-log form.
Any ideas?
Thanks
Let logpr1 and logpr2 be log(data|model1) and log(data|model2), respectively, and suppose
In [57]: logpr1 = -802
In [58]: logpr2 = -800
If you try to express those as probabilities (not logarithms of probabilities), you get 0:
In [59]: np.exp(logpr2)
Out[59]: 0.0
Now you want to compute
log(Pr(data|model1) / (Pr(data|model1) + Pr(data|model2))),
which you can also write as
log(Pr(data|model1)) - log(Pr(data|model1) + Pr(data|model2)).
For the last term, you can use the function numpy.logaddexp (which is the essential tip in this answer; see also scipy.misc.logsumexp). So your calculation is:
In [60]: logp = logpr1 - np.logaddexp(logpr1, logpr2)
In [61]: logp
Out[61]: -2.1269280110429918
In this case, that number is not very small. In fact, you can express it as a plain probability:
In [62]: np.exp(logp)
Out[62]: 0.11920292202211526
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
How can I check if the result of multiplying two amounts is equal to a certain total give or take a few cents. For example: 5.57 * 2.92 = 16.2644 and 3.25 * 5 = 16.25.
I am increasing the first amount which is the stake by 0.01 each time to try find the closest amount to the total, the second amount does not change.
If you're making financial-type calculations in Python (or any programming language), you do not want to use floating point numbers (http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
Instead, be sure to at least use the decimal module, which will give you arbitrary-precision decimal numbers (http://docs.python.org/2/library/decimal.html).
As for your actual problem:
from decimal import Decimal
r1 = Decimal("5.57") * Decimal("2.92")
r2 = Decimal("3.25") * Decimal("5")
epsilon = Decimal("0.01")
if abs(r1 - r2) <= epsilon:
print "Almost equal!"
decimal is good.
But to compare two floats within a tolerance:
tolerance = 0.04
if abs(number1 - number2) < tolerance:
print('the numbers are close')