# scalar^[vector]?

I feel really stupid like this should be obvious, but I can't figure out how to do it.

v = vector([1,2,3])
2^v


should give me

[2, 4, 8]


I can't find any other way to do this without writing a function.

edit retag close merge delete

Sort by » oldest newest most voted

Hello,

In Python (and hence Sage) you have very useful list comprehension

sage: my_list = [1, 2, 3, 4]
sage: [2^i for i in my_list]
[2, 4, 8, 16]


If you use vectors, you can alternatively do

sage: v = vector([1, 2, 3, 4])
sage: v.apply_map(lambda x: 2^x)
(2, 4, 8, 16)


Vincent

more

That makes writing the function easier, but for readability in the middle of an equation it leaves a lot to be desired. vdelecroix's answer is perfectly fine. I just wanted to add that if you insist on being able to use 2**v then maybe you will like numpy. See here for an example.

Update: It is possible to use 2.^v from within sage if v is a numpy array (see link above).

more

2.^x

works.

I guess I don't understand the relationship between sage and numpy or scipy or really any of the packages. Why is numpy not the default. What are the implications of doing the import? Are numpy vectors going to interact with the plotting correctly? Etc.

Ugh, I didn't even notice the difference between "through sage" and "with python". .^ works in one and errors in the other, while ^ is the reverse. I don't understand. What document gives a map for how all these things interact?

You are right, that works. I'll update the answer, thanks!

Numpy is a Python package intended for scientific computing and you have the option of using it through Sagemath. Doing the import will load the array function from numpy (in this case). I can't think of any errors you can run into if you try to plot from numpy arrays.

In Python ^ stands for bitwise xor. Sagemath was designed to override the meaning of ^ to be exponentiation. If you want to keep on the safe side you can just use ** which means exponentiation in both Python and Sagemath. A bit of this is explaned here.

Right, I know what numpy is. I just assumed the default python-like interaction I'm doing in a sagecell WAS numpy. Instead it's another language? Or something?

It is "the same language", it is just that Sagemath has its own way of defining/handling vectors, and Numpy has also its own way of handling them, they are just meant for different purposes. Which one to use? That depends on what you want to do.