错误使用np.where [英] Incorrect use of np.where

查看:103
本文介绍了错误使用np.where的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试使用两个步长来计算错误,一个步长是另一个步长的两倍.我设置了两个温度数组,它们使用两个不同的步长进行计算.当我注意到在循环中调用它以打印时间= 5分钟的温度值时,我为错误获取了疯狂的值,这是我写错了.如果我用任何数字代替它,它将输出相同的值.在这种情况下np.where(t = 5)是否使用不正确?对于每个不同的步长,都会生成一条曲线,该曲线的温度值对应于每次.我希望能够将时间步长的值及其相应的错误打印出来.

So I am trying to calculate an error by using two step sizes, one twice the size of the other. I set up two temperature arrays which are being calculated using two different step sizes. I was getting crazy values for my error when I noticed that inside my loop where I call it to print the value of temperature at time = 5 minutes, I have written it wrong. If I substitute it for any number really it prints the same value. is np.where(t=5) being used incorrectly in this case? For each different step size, there is a curve produced which has a temperature value corresponding to each time. I would like to be able to print the values of the timesteps with their corresponding errors.

for j in dt_values:
    t = np.arange(0,100,j) #time
    te = np.zeros(len(t)) #temperature array
    te[0] = te_init 
    te2 = np.zeros(len(t)) #second temp array
    te2[0] = te_init
    dt = j #timestep
    dt2 = 2*dt 
    def f(t,te):
        y = -r*(te - te_surr) # y is the derivative
        return y
    for i in range(1,len(t)): #eulers method for computing temperature 
        p1=f(t[i-1], te[i-1])
        p2 =f(t[i], te[i-1]+dt*p1)
        te[i] = te[i-1] + (p1 + p2)*(dt/2) 
        r1=f(t[i-1], te[i-1])
        r2 =f(t[i], te[i-1]+dt2*p1)
        te2[i] = te2[i-1] + (r1 + r2)*(dt2/2) 
    if np.where(t == 5): 
        print j
        print te[i] - te2[i]

推荐答案

首先,在由dt隔开的相同温度上循环,然后将dt翻倍.与尝试使用

First, looping over the same temperatures which are spaced by dt but then doubling dt makes no sense. It makes more sense to compare to the analytical solution as attempted in your previous post.

要在特定温度下打印结果的值,您可以-在您知道该值实际在数组内部的条件下-根据该条件对数组进行索引.

To print the value of the result at a certain temperature you may - under the condition that you know the value is actually inside the array - index the array by the condition.

例如

t = np.array([1,55,77])
x = np.array([1,2,3])
print x[t == 55]

在这种情况下:

import numpy as np 

r = 0.024 #cooling rate per minute
te_init = 90.0
te_surr = 17

def f(te):
    return -r*(te - te_surr) # the derivative

dt_values = [0.05, 0.025, 0.01, 0.005]

for dt in dt_values:
    t = np.arange(0,100,dt) #time
    te = np.zeros(len(t)) #temperature array
    te[0] = te_init 

    for i in range(1,len(t)): #eulers method for computing temperature 
        p1=f(te[i-1])
        p2 =f(te[i-1]+dt*p1)
        te[i] = te[i-1] + (p1 + p2)*(dt/2) 
        te_ana = te_surr - (te_surr - te_init)*np.exp(-r*t)

    print dt, 
    print te[t==10] - te_ana[t==10]

这篇关于错误使用np.where的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆