peer
peer

Reputation: 162

Subtracting a value in for loop in Python

I'd like to print the square roots of 1-10(backwards).

I'd also like to print the differences of each of these adjacent square roots.

import math as m

for i in range(10, -1, -1):
    print str(i) + ":   " + str(m.sqrt(i))
    print str(m.sqrt(i) - m.sqrt(i-1))

I'm currently getting a math domain error.

Upvotes: 0

Views: 1892

Answers (2)

shiva
shiva

Reputation: 5489

for negative integers use cmath module which is a built in module of python https://docs.python.org/2/library/cmath.html

I hope this answer helps you :

import math as m,cmath

for i in range(10, -2, -1):
    if i<=0:
        print str(i) + ":   " + str(cmath.sqrt(i))
        print str(cmath.sqrt(i)-cmath.sqrt(i-1))
    else:
        print str(i) + ":   " + str(m.sqrt(i))
        print str(m.sqrt(i) - m.sqrt(i-1))

and the output will be :

10:   3.16227766017
0.162277660168
9:   3.0
0.171572875254
8:   2.82842712475
0.182675813682
7:   2.64575131106
0.196261568281
6:   2.44948974278
0.213421765283
5:   2.2360679775
0.2360679775
4:   2.0
0.267949192431
3:   1.73205080757
0.317837245196
2:   1.41421356237
0.414213562373
1:   1.0
1.0
0:   0j
-1j
-1:   1j
-0.414213562373j

Upvotes: 1

Israel Unterman
Israel Unterman

Reputation: 13510

You indeed count until 0, but the line

print str(m.sqrt(i) - m.sqrt(i-1))

has i-1 which on i == 0 evaluates to sqrt(-1)

Upvotes: 2

Related Questions