简体   繁体   中英

write a loop to represent each polynomial from an array for n polynomials

import csv
import numpy
from sympy import *
import numpy as np
from numpy import *
import json

reader=csv.reader(open("/Users/61/Desktop/pythonlearning/generator1.csv","rU"),delimiter=',')
a=list(reader)
result=numpy.array(a)
print a 

b = []
for n in range(3):
    b.append(a[n+1][0:3])
print b
e = np.array(b)
f = e.astype(np.float)
print f

x = Symbol("x")
y = Symbol("y")

coeffs = f
F1 = numpy.poly1d(f[0])
F12 = np.polyder(F1)
print F12
F2 = numpy.poly1d(f[1])
F22 = np.polyder(F2)
print F22
F3 = numpy.poly1d(f[2])
F32 = np.polyder(F3) 
print F32

this is my coding and f is a array of numbers like this: [[ 9.68000000e-04 6.95000000e+00 7.49550000e+02] [ 7.38000000e-04 7.05100000e+00 1.28500000e+03] [ 1.04000000e-03 6.53100000e+00 1.53100000e+03]] . Basically, I want to assign the value of f to form polynomials, and then differentiate the polynomials. The results it like this 0.001936 x + 6.95 0.001476 x + 7.051 0.00208 x + 6.531 My question is how could write a loop for Fn if instead of 3 polynomials, I have n polynomials instead. How could I write a loop to obtain the differentiation for the n polynomials and can easy use the polynomials with different name of it. eg, F1 represent the first polynomial and F2 represent the second and so on. i tried sth like this, but it doesnt work

i = 1
if i < 3:
    F(i)=numpy.poly1d(f[i-1])
else:
    i = i+1

You need to use a loop to deal with a variable number of polynomials and a data structure to store them. Try using a dictionary, iterating using a for loop.

numberPolynomials = 3
F = {}
for n in range(1, numberPolynomials+1):
    F[n] = np.poly1d(f[n-1])
    F[(n, 2)] = np.polyder(F[n])
    print F[(n, 2)]

Now you can refer to the polynomial not as F1 , F2 , etc. but as F[1] , F[2] , etc. For what you had called F12 , F22 , F32 would then be F[(1,2)] , F[(2,2)] , F[(3,2)] . Though, if you aren't going to be using the originals you should overwrite them and probably just use a list.

This is assuming, you change the 3x imports of numpy to:

import numpy as np

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM