Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – creating NumPy arrays


The array class is the core of NumPy. Let's explore the various ways that we can create NumPy arrays:

import numpy

print("array:")
a = numpy.array([1,2,3,9,10,11])
print(a)

print("arange:")
b = numpy.arange(0.0, 10.0, 3.0/2)
print(b)

print("zeros:")
c = numpy.zeros(5,dtype=int)
print(c)

print("ones:")
d = numpy.ones((4,1), dtype=numpy.float64)
print(d)

print("ones, 2D array:")
e = numpy.ones((3,2))
print(e)

print("empty:")
f = numpy.empty((1,4), dtype=numpy.float32)
print(f)

The result should look like this:

What just happened?

In the first line of the script, we used the import statement to make NumPy functions and objects available to Sage. In order to keep NumPy types separate from Sage types with the same name, we access the NumPy types with the syntax numpy.type. In this example, we used several functions to create NumPy arrays. All of these functions accept the optional argument dtype, which specifies the type for the elements in the array...