简体   繁体   中英

How do I calculate the value of pi using series in python?

I'm a newbie in programming. Our class is using Python. I'm trying to calculate the value of pi over the range k = [0,5] and output the result indicating the value of k and the result value of pi. The equation we have to use is π=√12+(-3)^k/2k+1. Below is my code. I'm probably doing something wrong, but don't know. Thanks for your help.

k = range(0,5)
print("k:", list(k) )
series = [i+i for i in k]
print("series:", series)
sum = sum(series)

pi = math.sqrt(12)
numerator = (-3)pow(k)
denominator = 2(series) + 1
var = numerator/denominator
calculation = value/var
print("calculation")

Welcome to StackOverFlow.

So, there are a few things wrong with your code:

The first thing is that you should have the import math statement at the start of your code (unless you just excluded it). This allows you to use math.sqrt() and math.pow()

The next thing is that for the line that says numerator = (-3)pow(k) you should instead write numerator = math.pow(-3, k) The first argument in math.pow is the number you're using, and the second is the exponent that is applied to that number.

So your code should then look like this:

import math

k = range(0,5)
print("k:", list(k) )
series = [i+i for i in k]
print("series:", series)
sum = sum(series)

pi = math.sqrt(12)
numerator = math.pow(-3,k)
denominator = 2(series) + 1
var = numerator/denominator
calculation = value/var
print("calculation")

And even then, we still run into some problems... You're trying to raise -3 to the k power, but you initialize k as a range, from 0 to 5. You can't do this.

You want to raise -3 to the k power, and k is each number between 0 and 5. So, considering that this looks like a homework question, you'll have to figure out how to use each number in the range, and set it equal to k. Then calculate the value of pi for k = 0, then for k = 1, and on.

You might want to consider using a for loop, or list comprehension if you're not allowed to use loops yet.

Otherwise , take a look at this other StackOverflow post

I have to solve the same problem for my Python class, but it's (-3)^-k. I'm wondering if that's a transcription error you made. If so, you may have better results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM