Precise Python 2.7 calculation including Pi [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I am working on a small program that calculates different things related to orbital mechanics, such as the semi-major axis of an orbit, velocity etc. (No experience in this subject is required to answer this).
Everything worked out well, until I tried to calculate the orbital period (a formula where I had to use Pi):
T = 2π √ a3 / µ (Click for image)
Where T is time in seconds, a is the semi-major axis, and µ is the standard gravitational parameter.
Now, my problem is that my program does not calculate it very precise, as the result of the formula is a bit off; for example: a circular orbit at an altitude of 160km should take approx 88 minutes, but my program tells me an approx of 90 minutes and 37 seconds.
My code:
#the standard gravitational parameter of the Earth
gravPara = 3.986004418*10**14
#the semi-major axis of the orbit (the radius of the Earth + the apoapsis and periapsis of your orbit / 2)
semiMajor = (bodyDia + ap + pe) / 2
#formula to calculate orbital period
timeSeconds = (2 * math.pi) * math.sqrt(semiMajor**3 / gravPara)
#making the result appear as minutes and seconds instead of just seconds
timeMinutes = 0
while (timeSeconds > 60):
timeSeconds = timeSeconds - 60
timeMinutes = timeMinutes + 1
#round the variable to store seconds
round(timeSeconds, 0)
#print the result
print timeMinutes
print timeSeconds
So my question is: is it an error in my code, or is math.pi not very precise when used together in such a formula? Should I store it as a float and use the float instead or should I split up the calculation into multiple pieces?
I would be very thankful if you could help me out on this one, as searching through the Python reference as well as other forums did not get me very far.
PS: when using print math.pi it returns a precise value of Pi, so the math.pi function seems to be working correctly.

math.pi is a float with 15 decimals: 3.141592653589793
As per chepners comment to your original post, that equates to about the size of an atom when calculating spheres the size of the earth.
So to answer your question: it's not math.pi

Okay - seems like I have found the solution to my problem; while editing my question to include my calculation for the variable semiMajor, I realized I forgot to include parentheses around bodyDia + ap + pe, which caused faulty prioritizing, leading to the not-very-precise calculation.
So it was just a silly mistake in my code, and it was easily solved by adding two parentheses.
Thank you for taking your time.

Related

How does the choice of units impact numerical precision? [closed]

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.

10-sized subset with maximal sum less than K [closed]

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!

Calculating Percentage in Python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to calculate percentage in Python, by hand this works fine but in python this formula for some reason does not work. I tried multiple ways but just not getting correct results.
getPercent = lambda part, whole: float(1 - (float(part)/float(part))) * 100
Val1= float(3194.15)
Val2= float(3163.84)
getPercent(Val2, Val1)
Output:
0.0
output should be:
0.95
Just use whole instead of part in the denominator.
getPercent = lambda part, whole: float(1 - (float(part)/float(whole))) * 100
Val1= float(3194.15)
Val2= float(3163.84)
getPercent(Val2, Val1)
Try it online!
you haven't used whole in your lambda function
getPercent = lambda part, whole: float(1 - (float(part)/float(whole))) * 100
Val1= float(3194.15)
Val2= float(3163.84)
getPercent(Val2, Val1)
# output 0.9489222484855064
You need to divide by whole. To get just two decimal places:
get_percent = lambda part, whole: float(1 - part / whole) * 100
val_1 = float(3194.15)
val_2 = float(3163.84)
a_float = get_percent(val_2, val_1)
print("{:.2f}".format(a_float))
Returning:
0.95

PYTHON : Which is the best way to find distance between two points based on latitude/longitude using python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I Am developing a location based app using python django. I want to find the distance between two points based on latitude/longitude. I found several answers but the final result(distance) is different in each. Please find me the best way to find the distance. Thanks
From your comments, i am assuming you need to calculate a short distance less than 50 miles,
The easiest less accurate method would be to coordinate point distance formula, `aka, pythagorean distance formula
where a,b is obviously the latitude, longitude pair. Now one degree of latitude = 68~69miles or 111km. Remember this is just an approximation.
Just multiply the result of the equation with the latitude miles. This gives a rather crude filter when coming to short distance, i use this to filter by distance when i need to make to make to many calculations, using google api to show results can be rather expensive(time, bandwidth, quota wise) considering my application needs to filter about 100 results per search. Also i suggest to add in a 20~30% variation to include actual road distance.
Ok. If your still reading this then you need more accurate result.
Then use this, remember to convert this code to python format. I just used the javascript code with me.
function getDistanceLatLong(lat1,Long1,lat2,Long2) {
var RK = 6371; // Radius of the earth in km
var RM = 3959;
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLong = deg2rad(Long2-Long1);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = RK * c; // Distance in kiloMeters choose this or
var d = RM * c; // Distance in Miles
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}

Check if sum of two amounts is equal to a certain total with some tolerance [closed]

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')

Categories