0

I have this code:

n = int(input("Enter a positive integer n:\n"))
x = float(input("Enter a positive real number x :\n"))

def f(term_, i):
    return term_*x/(i-1)

sum = 1
for i in range(1, n+1):
    term = 1
    for k in range(2*i, 0, -1):
        term = f(term, k+1)  
    sum = sum + term * (-1) **i

print("w =",sum)

and I have a test case:

n = 5
x = 3.14
w = -1.0018168365436917

the code is supposed to return -1.0018168365436917, but it is currently returning -1.0018168365436928

No importing of libraries to round off is permitted to do this task. Can anyone offer some advice

bobthebuilder
  • 75
  • 1
  • 6
  • 4
    Make sure you understand [Is floating point math broken?](https://stackoverflow.com/q/588004/5987) – Mark Ransom Oct 26 '22 at 14:03
  • 1
    This is a normal floating point rounding issue. Basically, the value you're getting is close enough. You can't expect it to be exact, since that will vary from one machine to another. For example, some machines have internal floating point registers that are larger than 64 bits. On those machines, the answers will be slightly different. – Tom Karzes Oct 26 '22 at 14:05
  • Given the nature of floating point error -- there is little reason to think that the code is *really* supposed to return `-1.0018168365436917` . That itself is probably an approximation of the exact answer, just one that must have been computed using a different sequence of operations. – John Coleman Oct 26 '22 at 14:22

0 Answers0