Book Image

NumPy Cookbook

Book Image

NumPy Cookbook

Overview of this book

Today's world of science and technology is all about speed and flexibility. When it comes to scientific computing, NumPy is on the top of the list. NumPy will give you both speed and high productivity. "NumPy Cookbook" will teach you all about NumPy, a leading scientific computing library. NumPy replaces a lot of the functionality of Matlab and Mathematica, but in contrast to those products, it is free and open source. "Numpy Cookbook" will teach you to write readable, efficient, and fast code that is as close to the language of Mathematics as much as possible with the cutting edge open source NumPy software library. You will learn about installing and using NumPy and related concepts. At the end of the book, we will explore related scientific computing projects. This book will give you a solid foundation in NumPy arrays and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project through examples. "NumPy Cookbook" will help you to be productive with NumPy and write clean and fast code.
Table of Contents (17 chapters)
NumPy Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Sending a NumPy array to JPype


In this recipe, we will start a JVM and send a NumPy array to it. We will print the received array using standard Java calls. Obviously, you will need to have Java installed.

How to do it...

First, we need to start the JVM from JPype.

  1. Start the JVM.

    JPype is conveniently able to find the default JVM path:

    jpype.startJVM(jpype.getDefaultJVMPath())
  2. Print hello world.

    Just because of tradition, let's print hello world:

    jpype.java.lang.System.out.println("hello world")
  3. Send a NumPy array.

    Create a NumPy array, convert it to a Python list, and pass it to JPype. Now, it's trivial to print the array elements:

    values = numpy.arange(7)
    java_array = jpype.JArray(jpype.JDouble, 1)(values.tolist())
    
    for item in java_array:
        jpype.java.lang.System.out.println(item)
  4. Shutdown the JVM.

    After we are done, we will shutdown the JVM:

    jpype.shutdownJVM()

    Only one JVM can run at a time in JPype. If we forget to shutdown the JVM, it could lead to unexpected errors. The program output is as...