randint函数_Python:随机生成一点,一步步走到交点由两个函数所构成者

我的本意,是模仿庸俗经济学供需均衡曲线的动态运动。为此,我先设计了一个简单点的程序。

此程序,先设定二个非常简单的函数,二者相交於一点。

再生成一个点,此点是随机的,有可能出现在特定范围内任意坐标上。其横纵坐标值皆为整数。

然后,由该点横坐标,求二个函数相应自变量(即横坐标值)所对应的纵坐标值。

再由该点纵坐标值,对比二个函数相应诸纵坐标值,据其特定大小关系,移动此点。

重复此移动过程,直至该点移动至二个函数的交点。

并画出函数图像及该点的运动轨迹,以供参考。

代码如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct  8 10:54:17 2020

@author: abc
"""
import numpy as np
import matplotlib.pyplot as plt
import random
import time


def formulas():
    """Formulas here can be changed."""
    global x, y1, y2
    y1 = -x + 10
    y2 = x + 10


def get_xy_list():
    """Get list of (x, y)."""
    global xy, i
    xy.append([x, y])
    time.sleep(0.1)
    i += 1


# the picture of two functions
x = np.arange(-10, 10, 1)
formulas()
plt.plot(x, y1)
plt.plot(x, y2)
plt.axis("equal")
plt.show()

# ensure starting point
x = random.randint(-10, 11)
y = random.randint(-10, 11)
xy = []
xy.append([x, y])    # starting point first

i = 0
# move the point to the meeting point
while True:
    formulas()
    print("Keep moving! Step:", i)
    if y >= y1 and y > y2:    # up(and left line)
        y -= 1
        get_xy_list()
    elif y > y1 and y <= y2:    # right(and up line)
        x -= 1
        get_xy_list()
    elif y <= y1 and y < y2:    # down(and right line)
        y += 1
        get_xy_list()
    elif y < y1 and y >= y2:    # left(and down line)
        x += 1
        get_xy_list()
    else:    # meeting point
        print(xy)
        break

# the moving path of the point
lenth = len(xy)
x, y = [], []
for i in range(lenth):
    x.append(xy[i][0])
for i in range(lenth):
    y.append(xy[i][1])
# print(x, y)
plt.plot(x, y)
plt.show()

并分享相应函数图像,及若干点移路径图:

b4899651929fa28c38d99562ad86c634.png

41f01ee6833f18fada0b39ceb56071d0.png

997affc2ace031257c8c0b373635e3eb.png

5c8a8efb85a8aa6401eccfb95a9a1c00.png

61ee525bfbac0467a20a7059b542c098.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值