如何将这个 while 循环变成 for 循环并输出一个带有浮点值的列表?

How to turn this while loop into a for loop and output a list with float values?

我正在为我的论文编写这个 Python 代码。比方说

x1 = 0.1
x2 = 0.5
y1 = 0.1
y2 = 0.99
d = 0.1

def Calculate():
  tan_theta = ((y2-y1)/(x2-x1))
  theta = math.atan(tan_theta)

  i = x1  
  while (i < x2):
    print(i)
    i = i + d * math.cos(theta)

  j = y1
    while (j < y2):
      print(j)
      j = j + d * math.sin(theta)

Calculate()

输出的值是正确的:

0.1
0.140993850103
...

0.1
0.191211316479
...

但我需要它们在列表中,例如:

[0.1  0.140993850103  ...]
[0.1  0.191211316479  ...]

我还需要输出成为一个列表,并做了一些以前做过的例子,比如 但它对我不起作用。

  result_list = []
  i = x1  
  while (i < x2):
    i = i + d * math.cos(theta)
    result_list.append(i)
    print(i)

result_list2 = []
  j = y1
    while (j < y2):
      j = j + d * math.sin(theta)
      result_list2.append(j)
      print(j)

它仍然输出与之前相同的结果,甚至输出超出范围的值。

我还尝试通过使用 numpy 使用 For 循环,因为我正在处理浮点值。我尝试使用:

import numpy as np

  for i in [np.arange(x1, x2, x1 + d * math.cos(theta))]:
    print(i)

  for j in [np.arange(y1, y2, y1 + d * math.sin(theta))]:
    print(j)

但我得到的值是:

[0.1  0.24099385 0.3819877]
[0.1  0.29121132  0.48242263  0.67363395  0.86484527]

哪些是错误的。 我也应该得到相同数量的值(即 3 'x' 值和 3 'y' 值而不是 3 'x' 和 5 'y'.

能想到的都做完了,不知道怎么进步了。

我认为最 Pythonic 达到你想要的东西的方法就是创建你自己的 float_range 来模拟 range,例如:

import math

x1 = 0.1
x2 = 0.5
y1 = 0.1
y2 = 0.99
d = 0.1


def float_range(beg, end, increment):
    while beg < end:
        yield beg
        beg += increment


def Calculate():
    tan_theta = (y2 - y1) / (x2 - x1)
    theta = math.atan(tan_theta)

    list_x = list(float_range(x1, x2, d * math.cos(theta)))
    print(list_x)

    list_y = list(float_range(y1, y2, d * math.sin(theta)))
    print(list_y)


Calculate()

此外,您可以在 for 循环中使用它,例如:

for x in float_range(y1, y2, d * math.sin(theta)):
    print(x)