0

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.

2
  • 4
    sqrt(-1) is a domain error, try range(10, 0, -1) Commented Jan 16, 2017 at 7:05
  • 1
    and sqrt(-2) has the the same effect Commented Jan 16, 2017 at 7:07

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.