在python中

时间:2015-11-03 23:22:02

标签: python generator physics geometry points

我的任务是在一个看不见的圆的同心环上产生均匀(或多或少)的间隔点。该函数应该采用半径列表,以及给定半径作为参数绘制的点数。例如,对于半径为0,它应该在(0,0)处绘制1点。对于半径为1的圆,它应沿圆的圆周绘制10个点,间隔2pi / 10的角度。对于半径为2的圆,沿圆周的20个点,以2pi / 20的角度间隔开。

生成器应采用以下参数:

n,r_max,m

并且应该在半径

处生成坐标对的环

r_i = i * r_max / n,其中i = 0,1,..,n。

每个环应该有n * i个点均匀分布在θ中 对于i = 0,n_i = 1; n_i = mi for i> 0

当像这样调用函数时:

for r, t in genpolar.rtuniform(n=10, rmax=0.1, m=6):
      plot(r * cos(t), r * sin(t), 'bo')

它应该返回一个看起来像的情节: Plot

这是我到目前为止所提出的:

def rtpairs(R, N):
        R=[0.0,0.1,0.2]
        N=[1,10,20]
        r=[]
        t=[]
        for i in N:
                theta=2*np.pi/i
            t.append(theta)

        for j in R:
            j=j
            r.append(j)

    plt.plot(r*np.cos(t),r*np.sin(t), 'bo')
    plt.show()

但我很确定使用两个for循环有一个更有效的方法。

非常感谢

5 个答案:

答案 0 :(得分:6)

我明白了。代码如下:

import numpy as np
import matplotlib.pyplot as plt

T = [1, 10, 20, 30, 40, 50, 60]
R = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]



def rtpairs(r, n):

    for i in range(len(r)):
       for j in range(n[i]):    
        yield r[i], j*(2 * np.pi / n[i])

for r, t in rtpairs(R, T):
    plt.plot(r * np.cos(t), r * np.sin(t), 'bo')
plt.show()

答案 1 :(得分:1)

这是执行此操作的一种方法。

import { Component, OnInit } from '@angular/core';
import { LoggerService } from '../services/LoggingService/logger.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';


@Component({
  selector: 'app-generator',
  templateUrl: './generator.component.html',
  styleUrls: ['./generator.component.css']
})
export class GeneratorComponent implements OnInit {

  private name: string;
  private person: string;
  private shortage: string;
  private id: string;
  private area: string;

  private form: FormGroup;
  private formControls = {};

  constructor(
    private logger : LoggerService
  ) { 
    let validators = [];

    //these three fields are required
    validators.push(Validators.required);
    this.formControls[this.name] = new FormControl(this.name, validators);
    this.formControls[this.id] = new FormControl(this.id, validators);
    this.formControls[this.area] = new FormControl(this.area, validators);
    //these field is required + no special chars are allowed
    validators.push(this.noSpecialChars);
    this.formControls[this.person] = new FormControl(this.person, validators);

    //this field is required + no special chars allowed + length=3
    validators.push(Validators.minLength(3));
    validators.push(Validators.maxLength(3));
    this.formControls[this.shortage] = new FormControl(this.shortage, validators);
    //add formControls to my form
    this.form = new FormGroup (this.formControls);
  }

  ngOnInit() {

  }

  cancelCreation() {
    this.logger.info("Cancelling")
  }

  submit() {
    this.logger.info("Submitting");
  }
  // dont accept special chars
  noSpecialChars( c: FormControl) {
    let REGEXP = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/);

    return REGEXP.test(c.value) ? {
      validateId: {
        valid: false
      }
    } : null;
  }

}

当您在适当的列表中传递此函数时,一个函数具有每个圆的半径,另一个函数具有所需的点数,它将返回坐标数组的列表,每个圆具有一个。

<div class="total-div">
  <h1 id="headline">Headline</h1>  
  <hr>
  <form [formGroup]="form">
  <div class="block">
    <h2 class="subtitle">Info:</h2>
    <label>Name:</label>
    <input formControlName="{{name}}" placeholder="Name" class="outer-input"/> 
    <p>
    <label>Number:</label>
    <input formControlName="{{number}}" placeholder="Projektnummer"  class="outer-input"/> 
    </p>
    <p>
      <label>Area:</label>
      <input formControlName="{{area}}" placeholder="Area"  class="outer-input"/>
    </p>
    <hr class="sep">

    <h2 class="subtitle">Personal Info:</h2>

      <p>
        <label>Person:</label>
        <input formControlName="{{person}}" placeholder="person"  class="inner-input"/>
        <label>Shortage:</label>
        <input formControlName="{{shortage}}" placeholder="shortage" class="inner-input"/>
      </p>

    <hr class="sep">

    <button id="btn_create" (click)="submit()" [disabled]="!form.valid">Submit</button> <button id="btn_cancel" (click)="cancelCreation()">Cancel</button>
  </div>
  </form>
</div>

这些可以绘制如下。

import numpy as np
import matplotlib.pyplot as plt

def circle_points(r, n):
    circles = []
    for r, n in zip(r, n):
        t = np.linspace(0, two_pi, n)
        x = r * np.cos(t)
        y = r * np.sin(t)
        circles.append(np.c_[x, y])
    return circles

enter image description here

在这里,我们看到了更多圈子的结果。

r = [0, 0.1, 0.2]
n = [1, 10, 20]
circles = circle_points(r, n)

enter image description here

答案 2 :(得分:1)

您可以通过以下方式实现这一目标。

def circles(c_list: List[int]):
    g_d_list = []  # graph data list
    for g in c_list:
        # create length of circle list. In this instance
        # i'm multiplying by 8 each time but could be any number.
        lg = [g] * (8*g)
        ang = 360/len(lg)  # calculate the angle of each entry in circle list.
        ang_list = []
        for i in range(len(lg)+1):
            ang_list.append(ang*i)
        for i, c in enumerate(lg):
            # calculate the x and y axis points or each circle. in this instance
            # i'm expanding circles by multiples of ten but could be any number.
            x_axis = 0 + (10*g) * math.cos(math.radians(ang_list[i+1]))
            y_axis = 0 + (10*g) * math.sin(math.radians(ang_list[i+1]))
            # tuple structure ((axis tuple), circle size, circle colour)
            g_d_list.append(((x_axis, y_axis), 1, 'r'))

    fig, ax = plt.subplots()
    for c in range(len(g_d_list)):
        circle = plt.Circle(g_d_list[c][0], radius=g_d_list[c][1], fc=g_d_list[c][2])
        ax.add_patch(circle)
    plt.axis('scaled')
    plt.axis('off')  # optional if you don't want to show axis
    plt.show()

当提供包含您需要的圈数的列表时,它会生成一个图表。例如 circles([1,2,3]) 返回。

enter image description here

答案 3 :(得分:0)

你必须循环遍历所有半径的整个圆圈,所以你的情节调用几乎停留在一些M * N过程中。

可以稍微改进代码细节。对于初学者,您的 R 列表已经包含您想要的值;没有必要构建具有相同值的新列表。您可以使用简单的列表理解构建 t 列表。

这是你想要的吗?

    N=[1,10,20]
    t = [2*np.pi/i for i in N]
    for R in N:
        plt.plot(R*np.cos(t),R*np.sin(t), 'bo')

    plt.show()

答案 4 :(得分:0)

我不了解python,但这个公式应该有所帮助。

int ringNumber = 0

int n = ringNumber-1

((n / n + 1)* 60)-60 =点之间的度数(除了环零点,以点为中心