i need more decimal places for pi calculation [closed] - python

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 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm trying to make a Pi calculator in python but I need more decimal places.
it would help a lot if someone edited my code and carefully explained what they did.
this is the code I'm using.
import math
d = 0
ans = 0
display = 0
while True:
display += 1
d += 1
ans += 1/d**2
if display == 1000000:
print(math.sqrt(ans*6))
display = 0
# displays value calculated every 1m iterations
output after ~85m iterations: (3.14159264498239)
I need more than 15 decimal places (3.14159264498239........)

You’re using a very slowly converging series for π²∕6, so you are not going to get a very precise value this way. Floating point limitations prevent further progress after 3.14159264498239, but you’re not going to get much further in any reasonable amount of time, anyway. You can get around these issues by some combination of
micro-optimising your code,
storing a list of values, reversing it and using math.fsum,
using decimal.Decimal,
using a better series (like this one),
using a method that converges to the value of π quickly, instead of a series (like this one),
using PyPy, or a faster language than Python,
from math import pi.

you could try with a generator:
def oddnumbers():
n = 1
while True:
yield n
n += 2
def pi_series():
odds = oddnumbers()
approximation = 0
while True:
approximation += (4 / next(odds))
yield approximation
approximation -= (4 / next(odds))
yield approximation
approx_pi = pi_series()
for x in range(10000000):
print(next(approx_pi))

Related

Check if the length of the range divided by range element has no division remainder [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 2 years ago.
Improve this question
The code below shall show a specific comment if the number of elements in the array isn't integer-type number.
It works for dr=0.5 but not for dr=0.1 because print (4%0.1) returns 0.09999999999999978 instead of 0.
How can I change the code to get 4%0.1==0?
import math
limits_real=(-2,2)
dr=0.1
if (limits_real[1]-limits_real[0])%dr!=0:
print ('Inapropriate limits or elements')
It works for dr=0.5 but not for dr=0.1 because print (4%0.1) returns 0.09999999999999978 instead of 0.
Because floating point numbers have limitations that every programmer should know, see this:
https://docs.python.org/3/tutorial/floatingpoint.html
As showed at the end of above documentation, you can use decimal module, which works exacly right but is slower than normal floating point arihtmetics:
from decimal import Decimal
limits_real=(-2,2)
dr = Decimal("0.1")
if (limits_real[1] - limits_real[0]) % dr != 0:
print ('Inapropriate limits or elements')
Note that you should use a str while constructing the Decimal instance, do not use a float.
I found out only this solution :) At least it works
import math
limits_real=(-2,2)
dr=0.1
if (((limits_real[1] - limits_real[0]) * 1000) % (dr * 1000)) / 1000 != 0:
print ('Inapropriate limits or elements')

Python Iteration Homework [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 6 years ago.
Improve this question
I have 2 questions I need to ask for help with. One question I don't entirely understand so if someone could help me to that would be great.
Question One (the one I don't entirely understand):
One definition of e is
Formula for e
This can be calculated as my_e = 1/math.factorial(0) + 1/math.factorial(1) + 1/math.factorial(2) + 1/math.factorial(3) + …
Let n be the input number of the math.factorial() function. n successively takes on 0, 1, 2, 3 and so on. Find the smallest n such that the absolute value of (my_e – math.e) is less than or equal to 10-10. That is, abs(my_e - math.e) <= (10 ** -10).
I just don't entirely understand what I am being asked to do. Clarification would be great. Thanks!
Question 2:
Ask the user to type in a series of integers. Sum them up and print out the sum and the number of integers the user has entered.
My code
So what should happen is after I enter the numbers I want to enter and hit the enter key, it should calculate and print out "sum = 25 count = 3". The screenshot shows what error message I am getting.
Any help you have is welcomed and greatly appreciated.
As far as you first question goes:
>>> import math
>>> math.e
2.718281828459045
>>> sum(1.0/math.factorial(i) for i in range(5))
2.708333333333333
>>> abs(sum(1.0/math.factorial(i) for i in range(5)) - math.e) < 10**-10
False
>>> abs(sum(1.0/math.factorial(i) for i in range(30)) - math.e) < 10**-10
True
So, somewhere between n == 5 and n == 30 you get 10 decimal places for e. Create the sum term by term in a while-loop (instead of by using the sum function as I have, since you are unlikely to have seen that syntax yet). At each pass through the loop, compare the sum with math.e. Stop when you get the target accuracy. Return the final n.

How do i figure out the multiple of a number python [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 6 years ago.
Improve this question
ok, I am studying python in my computing course and i have been challenged with designing a code which validates a GTIN-8 code, I have came to a hurdle that i can not jump. I have looked on how to find the equal or higher multiple of a 10 and i have had no success so far, hope you guys can help me!
Here is a small piece of code, i need to find the equal or higher multiple of 10;
NewNumber = (NewGtin_1 + Gtin_2 + NewGtin_3 + Gtin_4 + NewGtin_5 + Gtin_6 + NewGtin_7)
print (NewNumber)
The easiest way, involving no functions and modules, could be using floor division operator //.
def neareast_higher_multiple_10(number):
return ((number // 10) + 1) * 10
Examples of usage:
>>> neareast_higher_multiple_10(15)
20
>>> neareast_higher_multiple_10(21)
30
>>> neareast_higher_multiple_10(20.1)
30.0
>>> neareast_higher_multiple_10(20)
30
We can also make a generalized version:
def neareast_higher_multiple(number, mult_of):
return ((number // mult_of) + 1) * mult_of
If you need nearest lower multiple, just remove + 1:
def neareast_lower_multiple(number, mult_of):
return (number // mult_of) * mult_of
To find the nearest multiple, you can call both these functions and use that one with a lower difference from the original number.

Round negative float numbers to floats [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am trying to round some negative floating numbers, the format i want is like the below print/format way, not the round. The problem is that the print approach is not "clean", since it outputs a string with spaces, I got this code from another similar question here in Stackoverflow. The question is how to format/round the numbers like the print below. Thank you
theta = 0.33161255787892263
math = 0 + (1-0) * (1-math.cos(theta))**5
round(math,8) # Result: 4.8e-07 #
print("{:18.8f}".format(math)) # Result: ' 0.00000048' #
You say "I want the result of the print but in a float number not string" and "The result returns to a negative power floating point number, i want to keep the decimal format as the string". But you can't do that because you have no control over the internal representation of a float: they are all stored in a binary form of scientific notation. See the Wikipedia article on floating-point numbers for details.
So it doesn't matter whether you do
v = 0.00000048
or
v = 4.8e-07
both of those statements have an identical effect.
Note that many fractional numbers that terminate when written in decimal may repeat when written in binary. The only fractions that terminate when written in binary are of the form n / (2 ** b), where n and b are integers. Thus even an innocuous-looking number like 0.2 doesn't terminate when converted to binary. (See the Wiki link for a fuller explanation). Because of this issue it's generally not a good idea to round floating-point numbers until you've finished all calculations with them.
If you convert a string to float and back again it has to be converted from decimal to binary and back again. So such an operation shouldn't be used in an attempt to "clean up" a number because of the possible rounding errors at each conversion step.
Of course, sometimes you do need to apply rounding to a float that you are going to continue calculating with, but if so, you should proceed with caution and make sure you really do understand what you're doing to your data.
...
There are a few other strange things with the code you posted.
math = 0 + (1-0) * (1-math.cos(theta))**5
Firstly, you should not use the name of a module that you've imported as a variable name. After the above statement is executed math now refers to the result of the calculation, not the math module, so if you tried to do x = math.cos(0.5) you'd get an error. Similarly, don't use int, str, list, etc as variable names.
Secondly, the 0 + (1-0) * is virtually useless. So the above statement could be re-written as
result = (1 - math.cos(theta)) ** 5
And the whole code snippet would become
#! /usr/bin/env python
import math
theta = 0.33161255787892263
result = (1 - math.cos(theta)) ** 5
print round(result, 8)
print("{0:.8f}".format(result))
output
4.8e-07
0.00000048

How to calculate sine and cosine without importing math? [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 9 years ago.
Improve this question
I started programming in python not too long ago and I am having trouble with a part of a program. The program will ask for input from the user and he can input: A, B, C, M, or Q. I have completed the A, M, and Q part but I can't figure out how to do the parts for B (calculate the sine of the number you want) and C (calculate the sine).
All the information I was given was:
The power series approximation for the sine of X can be expressed as:
sine(X) = X – (X3/3!) + (X5/5!) – (X7/7!) + (X9/9!) .... Note that an
individual term in that power series can be expressed as: (-1)k *
X2k+1 / (2k+1)! where k = 0, 1, 2, 3, ….
Oooh, and (but for this a while loop should do right?):
When computing the sine of X or the cosine of X, the program will expand the power series
until the absolute value of the next term in the series is less than 1.0e-8 (the specified epsilon).
That term will not be included in the approximation.
And I can't use import math.
Can anyone give me an idea of how I can do this? I sincerely have no idea of where to even start hahaha.
Thanks in advance!
***Hey guys, I've been trying to do this for the last 3 hours. I'm really new to programming and some of yours answers made it a bit more understandable for me but my program is not working, I really don't know how to do this. And yes, I went to speak with a tutor today but he didn't know either. So yeah, I guess I'll just wait until I get the program graded by my teacher and then I can ask him how it was supposed to be done. Thank you for all the answers though, I appreciate them! :)
>>> e = 2.718281828459045
>>> X = 0.1
>>> (e**(X*1j)).imag # sin(X)
0.09983341664682815
>>> (e**(X*1j)).real # cos(X)
0.9950041652780258
Verify
>>> from math import sin, cos
>>> sin(X)
0.09983341664682815
>>> cos(X)
0.9950041652780258
You'll probably get better marks if you sum up the series explicitly though
result = 0
n = 1
while True:
term = ...
result += term
if term <= epsilon:
break
n += 2
It seems that you aren't supposed to import math because you are supposed to write your own function to compute sine. You are supposed to use the power series approximation.
I suggest you start by writing a factorial function, then write a loop that uses this factorial function to compute the power series.
If you still can't figure it out, I suggest you talk to your teacher or a teacher's assistant.
Since you have a condition to finish the loop last_term < 1.0e-8, you should use a while:
while last_term > 1.0e-8:
You will need a counter to keep the count of k (starting from 0) and a variable to keep the last term:
k = 10 # some initial value
last_term = 0
while ...:
last_term = ... # formula here
and also a result variable, let' say sin_x:
while ...:
...
sin_x += last_term
Note: In the formula you are using factorial, so will need to define a function that computes the factorial of a number, and use it properly.

Categories

Resources