Python arithmetic progression with decimal numbers

Asked

Viewed 740 times

2

I was doing some exercises on the Internet and I came across the following: create a program that reads the first term and the reason and calculate the umpteenth term of this P.A. I did the program but I was in doubt "and if I inserted a decimal number instead of the reason or the first term?".

a1 = int(input('Insira o valor do primeiro termo: '))
r = int(input('Insira o valor da razão: '))
pa = a1 + (9 * r)
for c in range(a1, pa, r):
    print(c)

The problem is replacing "int" with "float". I get this error:

Traceback (Most recent call last):

File "c:/Users/ricar/Desktop/curso-python/teste/testes.py", line 4, in for c in range(a1, pa, r): Typeerror: 'float' Object cannot be Interpreted as an integer

1 answer

5


Yes, just use the float. The point is that you don’t need to use the range to calculate all terms of the sequence only to know the nth term. Imagine if the 1,000,000,000th term of the progression is requested?

For arithmetic progressions it is known that the nth term can be obtained through

ton = to1 + (n-1)*r

being the1 the first term and r the reason.

So just do it:

a1 = float(input('Primeiro termo: '))
r = float(input('Razão: '))
n = int(input('N: '))

an = a1 + (n-1)*r

print(f'O {n}º termo da PA é {an}')

The structure range works only with integers because all their behavior is based on sums and comparisons between values. From the initial value the step value is incremented as long as it is less than the final value. For floating point numbers this becomes critical because these operations can result in values unexpected, given the limitations of the system to represent them. For more information see:

  • I had no idea that the range structure only works with integers. Thanks for the clarification.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.