complex1.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # test basic complex number functionality
  2. # constructor
  3. print(complex(1))
  4. print(complex(1.2))
  5. print(complex(1.2j))
  6. print(complex("1"))
  7. print(complex("1.2"))
  8. print(complex("1.2j"))
  9. print(complex(1, 2))
  10. print(complex(1j, 2j))
  11. # unary ops
  12. print(bool(1j))
  13. print(+(1j))
  14. print(-(1 + 2j))
  15. # binary ops
  16. print(1j + False)
  17. print(1j + True)
  18. print(1j + 2)
  19. print(1j + 2j)
  20. print(1j - 2)
  21. print(1j - 2j)
  22. print(1j * 2)
  23. print(1j * 2j)
  24. print(1j / 2)
  25. print((1j / 2j).real)
  26. print(1j / (1 + 2j))
  27. ans = 0j ** 0; print("%.5g %.5g" % (ans.real, ans.imag))
  28. ans = 0j ** 1; print("%.5g %.5g" % (ans.real, ans.imag))
  29. ans = 0j ** 0j; print("%.5g %.5g" % (ans.real, ans.imag))
  30. ans = 1j ** 2.5; print("%.5g %.5g" % (ans.real, ans.imag))
  31. ans = 1j ** 2.5j; print("%.5g %.5g" % (ans.real, ans.imag))
  32. # comparison
  33. print(1j == 1)
  34. print(1j == 1j)
  35. # comparison of nan is special
  36. nan = float('nan') * 1j
  37. print(nan == 1j)
  38. print(nan == nan)
  39. # builtin abs
  40. print(abs(1j))
  41. print("%.5g" % abs(1j + 2))
  42. # builtin hash
  43. print(hash(1 + 0j))
  44. print(type(hash(1j)))
  45. # float on lhs should delegate to complex
  46. print(1.2 + 3j)
  47. # negative base and fractional power should create a complex
  48. ans = (-1) ** 2.3; print("%.5g %.5g" % (ans.real, ans.imag))
  49. ans = (-1.2) ** -3.4; print("%.5g %.5g" % (ans.real, ans.imag))
  50. # check printing of inf/nan
  51. print(float('nan') * 1j)
  52. print(float('-nan') * 1j)
  53. print(float('inf') * (1 + 1j))
  54. print(float('-inf') * (1 + 1j))
  55. # can't assign to attributes
  56. try:
  57. (1j).imag = 0
  58. except AttributeError:
  59. print('AttributeError')
  60. # can't convert rhs to complex
  61. try:
  62. 1j + []
  63. except TypeError:
  64. print("TypeError")
  65. # unsupported unary op
  66. try:
  67. ~(1j)
  68. except TypeError:
  69. print("TypeError")
  70. # unsupported binary op
  71. try:
  72. 1j // 2
  73. except TypeError:
  74. print("TypeError")
  75. # unsupported binary op
  76. try:
  77. 1j < 2j
  78. except TypeError:
  79. print("TypeError")
  80. #small int on LHS, complex on RHS, unsupported op
  81. try:
  82. print(1 | 1j)
  83. except TypeError:
  84. print('TypeError')
  85. # zero division
  86. try:
  87. 1j / 0
  88. except ZeroDivisionError:
  89. print("ZeroDivisionError")
  90. # zero division via power
  91. try:
  92. 0j ** -1
  93. except ZeroDivisionError:
  94. print("ZeroDivisionError")
  95. try:
  96. 0j ** 1j
  97. except ZeroDivisionError:
  98. print("ZeroDivisionError")