Your first calculation¶
This tutorial constructs a matrix, multiplies it, and reads the result. Complete installation first.
Add two scalars¶
The Python interface calculates with IEEE 754 binary64 values, corresponding
to C double. Results are Python floats.
Construct and multiply a matrix¶
HMath stores matrix values in row-major order. The list below represents
[[1, 2], [3, 4]].
from hmath import Tensor
with Tensor.matrix([1, 2, 3, 4], 2, 2) as matrix:
assert matrix.shape == (2, 2)
assert matrix.sum() == 10.0
with matrix @ matrix as product:
assert product.shape == (2, 2)
assert product.values() == [7.0, 10.0, 15.0, 22.0]
The product follows ordinary matrix multiplication:
Each with block releases its tensor when the block ends. Operators create
new tensors; they do not modify their operands.
Handle invalid input¶
The number of values must equal the product of the dimensions:
from hmath import HMathError, Tensor
try:
Tensor([1.0], shape=(2, 2))
except HMathError as error:
assert error.status == 2 # HMATH_SHAPE_ERROR
else:
raise AssertionError("An invalid shape was accepted")
Continue with NumPy interoperability, or consult the complete Python reference.