1

I am starting my adventure with Python. My current program is very simple, it has to calculate pi using Leibnitz formula, and stop working when module from "a" varibale is less than x. So far, it looks like this:

from math import fabs from math import pi x=float(input('Enter accuracy of calculating:')) sum=0 a=0 n=0 while True: a=float(((-1)**n)/(2*n+1)) sum+=a n+=1 result=sum*4 if fabs(a)<x: break print('Calculated pi:',result) print('Imported pi:', pi) 

It looks ok, but here's the problem: In my version of Geanie it works great, but on my friend's Geanie - it calculates 0.0. Also, on Ideone.com (without keyboard input, just e.g. x=0.0001) it also returns 0.0.

Does anyone knows where the problem is?

1 Answer 1

3

Try this

a=((-1)**n)/float(2*n+1) 

instead of this

a=float(((-1)**n)/(2*n+1)) 

Reason: I don't see a point to setting a itself to be a float, but setting the divisor or dividend in the division that produces a will ensure that Python doesn't cut the remainder (which is the default for integer division before Python 3.0).

Side issue: Your style doesn't match the official Python style guidelines, so you might want to change that.

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you VERY MUCH, it works perfect now. I didn't thought about Python cutting the remainder... And thanks for tip about Python style, I'll work on that. ;)
Sorry for double comment, but I cannot edit anything after 5 minutes... So, here's the post scriptum for the comment above: If I test program for 'e^(-06)' number, it treats it like string, and can't convert it to float... Any ideas how to enter exponent value without any problems?
The symbol for exponentiation in Python is **, not ^. You know that! :) Can you be clearer on exactly what is not being converted to a float -- like, can you write out the code?
Yes, sorry for '^', i'm used to it :D But if I enter 'e**(-06)' as input, it still takes that as string. I entered '3**4' as input, just for pure curiosity ;), and Python interpreted this as string. Here's the screenshot of console: s22.postimg.org/6gum0kg41/asdfasdfasdfasdfa.png It looks like everything what's not a number is treated as string :(
OK, I figured it out by myself! :) I just need to type: 1e-06 instead of e-06... It's so simple, that I'm ashamed of myself :) Anyway, thank you really much for help, thread solved ;)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.