Need to match exact decimal output Python - python

The German mathematician Gottfried Leibniz developed the following method to approximate the value of π:
π/4 = 1 - 1/3 + 1/5 - 1/7 + . . .
Write a program that allows the user to specify the number of iterations used in this approximation and that displays the resulting value.
An example of the program input and output is shown below:
Enter the number of iterations: 5
The approximation of pi is 3.3396825396825403
iteration = int(input("Enter the number of iteration: "))
list01 = []
list02 = []
y = 1
for x in range(1, iteration+1):
number = (1.0/y)
list01.append(number)
y += 2.0
#print(number)
for i in range(1, iteration, 2):
neg = list01[i]*-1.0
list02.append(neg)
#print(neg)
comb = (sum(list01)) + (sum(list02)) + (sum(list02))
pi = comb*4.0
print("The approximation of pi is", pi)
With this code for:
1 iteration, output is 4.0 which matches the required output of 4
5 iteration, output is 3.339682539682539 which doesn't match the required output of 3.3396825396825403
10 iteration, output is 3.0418396189294015 which doesn't match the required output of 3.0418396189294032
999 iteration, output is 3.1425936543400352 which doesn't match the required output of 3.142593654340044

"""pure step by step Leibniz idea
'sign'-- sign switcher. If you need the sum of even divisors
summ +1/1 (n=0), +1/5 (n=2), +1/9 (n=4), sign is True.
With each odd divisible, 'sign' changes to False, changing the
sign of the next term, summ -1/3 (n=1), -1/7 (n=3), -1/11 (n=5), etc..
"""
iteration = int(input("n: "))
presumm = 0
div = 1
sign = True
for i in range(iteration):
presumm = presumm + 1 / div if sign else presumm - 1 / div
div += 2
sign = not sign
pi = presumm * 4
print(pi)
# n==5, output: 3.3396825396825403
# n==10, output: 3.0418396189294032
# n==999, output: 3.142593654340044

iterations = int(input("Enter the number of iterations: "))
answer = 0
d = 1
pos = True
for f in range(iterations):
if pos:
answer += 1 / d
pos = False
else:
answer -= 1 / d
pos = True
d += 2
final = 4 * answer
print("The approximation of pi is " + str(final))

For an alternating sum, the "floating point error" should be small as can be starting from the small end:
# π/4 = 1 - 1/3 + 1/5 - 1/7 + ...
def leibniz(n_terms):
""" Return pi as per alternating sum of n_terms odd stem fractions. """
if n_terms <= 0:
return 0
sum = .0
for stem in range(n_terms * 2 - 1, 0, -2):
# print(sum, float(1-(stem&2))/stem)
sum += float(1-(stem&2))/stem
return 4 * sum

Related

Why is the output always the same?

My task is to check whether or not a number's (maximum eight digits) individual digits cubed will equal the number inputted (has to remain as a string). For example, 215 would return 2 x 2 x 2 + 1 x 1 x 1 + 5 x 5 x 5 = 134 (not true).
371 = 3 x 3 x 3 + 7 x 7 x 7 + 1 x 1 x 1 = 371 (true)
The program is to continue forever until an input of 0 is made. I understand that I have to make a function before the main program. But my program never breaks even if I enter 0...
def sum_of_cubes(num):
num_string = str(num)
sum = 0
for i in num_string:
digit = int(i)
cube = digit * digit * digit
sum = sum + cube
return sum
def main():
while True:
number = input("Enter a number (max 8 digits): ")
result = sum_of_cubes(number)
print(result)
number_result= str(result)
if result == number:
print("Yes")
if result!= number:
print("No")
if number=='0':
break
main()
You should add the cubed numbers to the sum inside the for loop.
you currently have it outside, so it will add only the last digit's cubed number.
try this:
.
.
.
sum = 0
for i in num_string:
digit = int(i)
cube = digit * digit * digit
sum = sum + cube
return sum

Python Arithmetic Sequence Sum

How do I make a code that follows this? 1⋅2+2⋅3+3⋅4+…+(n−1)⋅n
For example, if n=5, the answer is 1⋅2+2⋅3+3⋅4+4⋅5=40.
n cannot be less than or equal to two or more or equal to 1000
This is my code for now but it doesn't work.
n = int(input())
if n>= 2 and n<=1000:
sum = 0;
numbers = range(1, n+1)
for amount in numbers:
if (amount % 2 == 1):
sum *= amount
else:
sum += amount
print(sum)
For every number between 1 and n-1 (inclusive), you need to multiply it by the following number, and then sum them all. The easiest way to represent this is with a comprehension expression over a range call:
result = sum(i * (i + 1) for i in range(1, n))
You need to reproduce exactly the scheme you give
for each number, mulitply it with itself-1, and sum that
def compute(n):
if 2 <= n <= 1000:
total = 0
for amount in range(1, n + 1):
total += amount * (amount - 1)
print(total)
But that's the same as multiplying each with itself+1, if you change the bound to get one step less
for amount in range(1,n):
total += amount * (amount + 1)
Then you can use builtin methos sum and a generator syntax
def compute(n):
if 2 <= n <= 1000:
total = sum(nb * (nb + 1) for nb in range(1,n))
print(total)
If you try to approach it mathematically, you can have the answer in a single expression.
Dry run your code. You will see that for n = 5, you are doing as follows:
Num of Iterations = 6 (1 -> 5+1)
Iteration 1
sum = 0 + 1 = 1
Iteration 2
sum = 1 * 2 = 2
Iteration 3
sum = 2 + 3 = 5
Iteration 4
sum = 5 * 4 = 20
Iteration 5
sum = 20 + 5 = 25
Iteration 6
sum = 25 * 6 = 150
In this, you are completely disregarding the BODMAS/PEMDAS rule of multiplication over addition in the process of regenerating and calculating the series
What you need to do is
Iteration 1:
sum = 0 + 2 * 1 = 2
Iteration 2:
sum = 2 + 3 * 2 = 8
Iteration 3:
Sum = 8 + 4*3 = 20
Iteration 4:
Sum = 20 + 5*4 = 40
Here, We have broken the step as follows:
For each iteration, take the product of (n) and (n-1) and add it to the previous value
Also note that in the process, we are first multiplying and then adding. ( respecting BODMAS/PEMDAS rule )
So, you need to go from n = 2 to n = 5 and on each iteration you need to do (n-1)*(n)
As mentioned earlier, the loop is as follows:
## Checks for n if any
sum = 0
for i in range(2, n):
sum = sum + (i-1)*i
print(sum)

sum = (1**2) + (2**2) - (3**2) + (4**2)-,...,+(n**2) program code in python

Write a program to show the sum of (1**2) + (2**2) - (3**2) + (4**2)-,...,+(n**2) program code in python using "for" and "While" loop.
Although I wrote only for + iteration as shown below in code but +,-,+,- iteration is much difficult. Here is my code of + iteration:
nstart = 1
nend = 4
count = 0
Sum = 0
for i in range(nstart,nend+1):
count+=1
d = i**2
Sum = Sum + d
print(count,'**2 = ', d )
print('Sum = ', Sum)
#This program print same as [(1**2,+ 2**2,+ 3**2= 9,+,,,,+n**2 and sum of them)]
Another option: use a sign variable and change it accordingly.
sum = 1**2
sign = 1 #positive
for i in range(2, n+1):
sum += sign * (i ** 2)
sign *= -1 #flip sign
You can do % 2 check to check for odd numbers and set the sign as + or - accordingly:
sum = 0
for i in range(1, n+1):
if i != 1 and i % 2:
sum -= (i ** 2)
else:
sum += (i ** 2)
For n value 4, this outputs 12.

complicated variable assignment

I usually do my incrementation this way:
n=0
n=n+1 # and never do n+=1
Now there is code that I am trying to comprehend and I'm struggling to understand it.
sum=0
temp = num
while temp > 0:
digit = temp % 10
# below is the line I do not understand
sum += digit ** power # what is happening here?. with power= len(str(num))
temp //= 10
if num == sum:
print num
This snippet is a piece to list the armstrong numbers.
In python ** is the sign for exponent, so x ** 2 is x^2 (or x squared).
x += g is the same as x = x + g
sum += digit ** power == sum = sum + (digit ** power)
while temp > 0:
digit = temp % 10
sum += digit ** power
temp //= 10
Take the last digit of temp
Add to sum the digit to the power of power
Delete the last digit of temp
suppose num = 34, then power becomes 2, so, for first iteration:
digit = 4
sum = 0 + 4 ** 2 # which is 0 + 16 = 16. Then adding to sum
so, digit ** power is digit to the power of 2
similarly, for second iteration:
digit = 3
sum = 16 + 3 ** 2 # which is 16 + 9 = 25

How can I reverse index and -1 each loop

value = input("Enter the binary value to convert to a decimal number.")
prod = 0
power = 0
ans = 0
for i in range (int(value)):
prod = ((int(value[*right most digit here*])) * ((2**power)))
ans = prod + ans
prod = 0
power + 1
else:
print (ans)
I am trying to create a binary calculator.
I believe I have the power part of the equation working as it begins with 2 ^ 0, then 2 ^ 1 for the next digit and so on. But I am having trouble getting the first part of the equation, the right most digit of the value inputted.
So let's say, 0101 was inputted. I want 1 * ( 2 ^ 0 ) in the first loop, 0 * ( 2 ^ 1) in the second loop, and so on; right to left. So with how indexing works in Python, how can I reverse index it so [4] is in the first loop, then [3] in the second loop, and so on.
Thanks for help.
However there are better options available, i am assuming you are clearing your basics. Following can be the options:
Note : You should use len(value) instead of int(value) in the loop.
# 1. When starting the loop from 0 (i.e. i=0). you can use ( len(value) - i )th index.'
for i in range (len(value)):
prod = ((int(value[len(value) - i - 1])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 2. Python also supports negative indexing, So you may run a loop from -1 to -len(value).
for i in range (-1,-len(value) - 1,-1):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 3. You can reverse the whole string in your first step and then loop from 0 to len(value)-1.
value = reversed(value)
for i in range (len(value)):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
But there are some bugs in the code (or may be lack on information). This code works only for unsigned integers. If you want it to work on signed numbers as well, you have to take 2's complement into consideration.
Below is a very simple code that works with signed numbers too (in case needed):
#convert binary string into decimal value. Works on 2's complement.
def binToDecimal(s):
neg = False
if s[0] == '1':
s = twosComp(s)
neg = True
#compute the decimal value
val = reduce(lambda x,y : int(x)*2+1 if y=='1' else int(x)*2,'0'+s)
#negate the value if the first bit is 1
return -val if neg else val
#return the 2's complement string
def twosComp(s):
s = list(s[::-1])
#take 1's complement
s = ['1' if i=='0' else '0' for i in s]
#take 2's complement
for i in range(len(s)):
if s[i] == '0':
#no carry will be generated in this case, so we break it.
s[i] = '1'
break
else:
s[i]='0'
# return 2's complement string
return ''.join(map(str,s))[::-1]
value = input("Enter the binary value to convert to a decimal number.")
power = 0
ans = 0
for i in reversed(value):
prod = int(i) * (2**power)
ans = prod + ans
power += 1
else:
print(ans)
Improved your code while keeping it as close to your code as possible. Your for loop was creating a list of 1 to whatever the value we input, that's not what you should be doing. One way of doing is, treating your input as a string (which basically is a list that can be iterated through) reverse it so you go from right to left, then do your operation on it on each value. You were trying to get the index of the location of the value input right? Why? Python is beautiful where you most likely don't need to directly tell the index of something.
value = input("Enter the binary value to convert to a decimal number.")
prod = 0
power = 0
ans = 0
for i in range(int(len(value))-1):
prod = ((int(value[-1])) * ((2**power)))
ans = prod + ans
prod = 0
power + 1
else:
print (ans)
You were doing the range of the value and not the input len so we use len() to get the length of the string that was inputted. -1 is there because the length of a string can be 3 for input 001 but if indexing 3 would be out of bounds because indexing starts at 0 not 1
Note that in Python a negative index value is accepted. Negative index means starts from the end of the list and count backwards, so I think that was the answer you were looking for.
For example if we have the list my_list=['a','b','c'] and we call my_list[-2] it will return 'b'
You have some mistakes in your code, so replace it with this:
value = input("Enter the binary value to convert to a decimal number: ")
value = int(value) # conversion from string to number
power = 0
ans = 0
while(value > 0):
lastDigit = value % 10 # last digit
value = value // 10 # cutting off last digit (for next iteration)
prod = lastDigit * (2 ** power)
ans = prod + ans
power = power + 1
print (ans)
Last digit is calculated as the remainder after division by 10 (value % 10)
and is cutting of by integer division by 10 (value // 10) - as in first grades of basic school: 27 % 10 = 7 27 // 10 = 2
Simpler way to achieve this with be to mention base as 2 with int(). For example:
>>> num = '110'
>>> int(num, 2)
6
In case you are looking for custom solution, you may create a function as:
def binary_string_to_int(binary_string):
int_num = 0
for i in binary_string:
int_num += int(i)
int_num *= 2
return int_num / 2
Sample run:
>>> binary_string_to_int('111')
7
>>> binary_string_to_int('101')
5

Categories

Resources