我想研究python中的符号函数。我想创建y(x) = x^2 + 2x + 3
并将其绘制在[1, 255]
范围内。我想使用subs()
函数通过使用for
循环来计算值。但是,当我运行该命令时,出现此错误:
IndexError('list index out of range')
你能帮我吗?
import numpy as np
import matplotlib.pyplot as plot
from sympy import *
a = [1,2,3]
x = Symbol('x')
fx = a[0]*x**2 + a[1]*x + a[2]
t = list(range(1,256))
y = np.zeros(256)
for i in t:
y[i] = fx.subs({x:t[i]})
plot.plot(t,y)
plot.show()
答案 0 :(得分:1)
只需替换为以下行:
import { Component, OnInit } from '@angular/core';
import { Observable, from, of, GroupedObservable } from 'rxjs';
import { distinct, map, mergeMap, toArray, groupBy } from 'rxjs/operators';
export class ModelA {
id: number;
name: string;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
models: Observable<ModelA[]>;
distinctModels: Observable<ModelA[]>;
groupedModels: Observable<ModelA[][]>;
ngOnInit() {
this.loadData();
}
loadData(): void {
this.models = of([
{id: 1, name: 'Name A'},
{id: 2, name: 'Name A'},
{id: 3, name: 'Name B'},
{id: 4, name: 'Name C'}
]);
this.distinctModels = this.models
.pipe(
mergeMap(models => models),
distinct(m => m.name),
toArray()
);
this.distinctModels.subscribe( m => console.log(m));
this.groupedModels = this.models
.pipe(
mergeMap(models =>models),
groupBy(model => model.name),
mergeMap(toArray()),
toArray()
);
this.groupedModels.subscribe( m => console.log(m));
}
}
问题在于代码中y = np.zeros(len(t))
for i in range(len(t)):
y[i] = fx.subs({x:t[i]})
的长度仅为t
,而255
的长度为y
,因为您定义了256
,因此y = np.zeros(256)
,因为没有Index Error
。我使用t[256]
是因为您的y = np.zeros(len(t))
点与y
(或t
)点一样多。顺便说一句,由于调用x
,极有可能在当前的绘图命令中出现错误。我将其简称为import matplotlib.pyplot as plot
而不是plt
输出