打印功能值

时间:2019-11-24 20:09:44

标签: python

打印函数y = (x ^ 2/2) -4x的值,其中x从-3到-1以0.2为增量

1 个答案:

答案 0 :(得分:0)

import numpy as np

x_range = np.arange(-3, -0.8, 0.2)
for x in x_range:
  y = (x**2)/2 - 4*x
  print("{:.2f} -> {:.2f}".format(x, y))

如果要存储每个x的y值:

import numpy as np

x_range = np.arange(-3, -0.8, 0.2)
y_vals = []
for x in x_range:
  y = (x**2)/2 - 4*x
  y_vals.append(y)

print(np.around(y_vals, decimals=2))

没有numpy:

y_vals = []
for x in range(-30,-8,2):
  x /= 10.0 # can't have floats in range()
  y = (x**2)/2 - 4*x
  y_vals.append(y)

print(y_vals)