Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2014
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. from numpy import *
  2.  
  3. def sum_of_indices(x, y, z):
  4. # What type are X, Y and Z ? Expect int or duck-type equivalent.
  5. # Getting 3 individual arrays
  6. print "Value of X is:"
  7. print x
  8.  
  9. print "Type of X is:", type(x)
  10. return x + y + z
  11.  
  12. a = fromfunction(sum_of_indices, (2, 2, 2))
  13.  
  14. Value of X is:
  15. 0
  16. Type of X is: int
  17. Value of X is:
  18. 1
  19. Type of X is: int
  20.  
  21. Value of X is:
  22. [[[ 0. 0.]
  23. [ 0. 0.]]
  24.  
  25. [[ 1. 1.]
  26. [ 1. 1.]]]
  27. [[[ 0. 0.]
  28. [ 1. 1.]]
  29.  
  30. [[ 0. 0.]
  31. [ 1. 1.]]]
  32. [[[ 0. 1.]
  33. [ 0. 1.]]
  34.  
  35. [[ 0. 1.]
  36. [ 0. 1.]]]
  37. Type of X is: <type 'numpy.ndarray'>
  38.  
  39. (array([[ 0., 0.], [ 1., 1.]]), array([[ 0., 1.], [ 0., 1.]]))
  40.  
  41. def fromfunction(function, shape, **kwargs):
  42. dtype = kwargs.pop('dtype', float)
  43. args = indices(shape, dtype=dtype)
  44. return function(*args,**kwargs)
  45.  
  46. >>> side = np.arange(2)
  47. >>> side
  48. array([0, 1])
  49. >>> x,y,z = np.meshgrid(side,side,side)
  50. >>> x
  51. array([[[0, 0],
  52. [1, 1]],
  53.  
  54. [[0, 0],
  55. [1, 1]]])
  56. >>> x+y+z #Result of your code.
  57. array([[[0, 1],
  58. [1, 2]],
  59.  
  60. [[1, 2],
  61. [2, 3]]])
  62.  
  63. >>> a
  64. array([[[ 0., 1.], # 0+0+0, 0+0+1
  65. [ 1., 2.]], # 0+1+0, 0+1+1
  66.  
  67. [[ 1., 2.], # 1+0+0, 1+0+1
  68. [ 2., 3.]]]) # 1+1+0, 1+1+1
  69.  
  70. def fromfunction(function, shape, **kwargs):
  71. . . .
  72. args = indices(shape, dtype=dtype)
  73. return function(*args,**kwargs)
  74.  
  75. array([[[ 0., 0.],
  76. [ 1., 1.]],
  77.  
  78. [[ 1., 1.],
  79. [ 1., 1.]]])
  80.  
  81. +
  82.  
  83. array([[[ 0., 0.],
  84. [ 1., 1.]],
  85.  
  86. [[ 0., 0.],
  87. [ 1., 1.]]])
  88.  
  89. +
  90. array([[[ 0., 1.],
  91. [ 0., 1.]],
  92.  
  93. [[ 0., 1.],
  94. [ 0., 1.]]])
  95.  
  96. =
  97.  
  98. array([[[ 1., 1.],
  99. [ 1., 2.]],
  100.  
  101. [[ 1., 2.],
  102. [ 2., 3.]]])
  103.  
  104. f([[0., 0.], [1., 1.]], [[0., 1.], [0., 1.]])
  105.  
  106. m = fromfunction(f, shape)
  107.  
  108. g = vectorize(f)
  109. m = fromfunction(g, shape)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement