So I answered this question on SO and probably did someone's homework along the way.
In the original question the OP has the answer
variable and wants it split to real and imaginary values with the original coefficient (q
in the original post) as an array for each q from 1 to 10, so you get an array of arrays looking like:
[[1,-0.39002422, 1.84237253, -0.39002422, -1.84237253, -0.10997578, 0.51949688,-0.10997578, -0.51949688j],
[2, ...]
...
[10, ...]]
There are two things I'm unsatisfied with in the answer I gave that are the reason I'm asking for a CR.
- The indexing: Isn't particularly readable, and I don't know how to make it more readable. For example
[q-1, 2*_+1]
. Would it have been better to create a variablej = q-1
becauseq-1
sees frequent use? Isn't that just moving the ugly to a different place? - The idea for the solution itself. The way I see it the original problem can be solved by splitting the answer array to a new array, but that feels somehow wrong. I can see several ways to create the new array, but I don't see a way to do it without creating the new array. Am I wrong and this is an OK solution or not, and why?
Thanks.
import numpy as np
export = np.empty([10,9])
for q in range(1,11):
a0=1
a1=3*q^2
a2=4*q
a3=np.sqrt(q)
a4=q
coeff=[a0, a1, a2, a3, a4]
answer = np.roots(coeff)
export[q-1, 0] = q
for _ in range(len(answer)):
export[q-1, 2*_+1] = answer[_].real
export[q-1, 2*(_+1)] = answer[_].imag
with open("/tmp/latest_foo.csv", "ab") as output_file:
np.savetxt(output_file, export, delimiter=",")