由于在 exp 中遇到溢出,无法在 Python在 Spyder 上中集成大指数,但适用于 WolframAlpha 图 1:w = 1e-5图 2 = w = 1e-2当 w=1e-2,点数 = 21,num_T = 300 时,我在图 2 中的尝试

如何解决由于在 exp 中遇到溢出,无法在 Python在 Spyder 上中集成大指数,但适用于 WolframAlpha 图 1:w = 1e-5图 2 = w = 1e-2当 w=1e-2,点数 = 21,num_T = 300 时,我在图 2 中的尝试

我一直在尝试使用 Spyder 上的 Python 复制 O'Dwyer 的论文“具有低维接触的热载流子太阳能电池中的电子和热传输”(Link to O'Dwyer Paper) 中的图 1 和图 2。>

要复制的数字

图 1:w = 1e-5

Figure 1

图 2 = w = 1e-2

Figure 2

方法

要找到吸收器温度 T_H,需要将由于辐射引起的净传入能量流 Qrad 和从热吸收器储层流出的净热流 Qabs 相等. 他们的方程如下:

Equations for Qrad and Qabs

图 1 和图 2 中的粗线图表示 Wurfel 的解,由以下方程给出:

Wurfel's Solutions

我在复制图 2 时取得了一些成功,其中 w=1e-2(我的结果如下所示)但没有成功获得图 1,其中 w=1e-5(下面的点和 num_T 指的是绘图点的数量和分别迭代的温度数)。

当 w=1e-2,点数 = 21,num_T = 300 时,我在图 2 中的尝试

My attempt at Figure 2

我想我目前在尝试使用 w=1e-5 使图 1 正常工作时遇到“exp 中遇到溢出”警告的问题。当我尝试计算 Qabs(请参阅下面“参数”函数中的代码)时,它给出了数量级约为 1e-70 的荒谬值。然而,当我在 WolframAlpha 中运行相同的方程时,我得到了更合理的结果。

例如,当 W = 1e-5、N = 1e12 和电压 = 0 V 时,T_H 值为 ~T_H = 1448K(参见图 1,左上图)。使用 WolframAlpha,我得到 4.54986×10^22对于 Qrad 和 4.83602×10^22 对于 Qabs (WolframAlpha solution for Qrad at w=1e-5,N=1e12,V=0) 和 WolframAlpha solution for Qabs at w=1e-5,V=0)),这是我在 Python 中想要的结果。在下面找到我所有的代码。

所有代码

import os
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.widgets import Slider,Button
import matplotlib.ticker as ticker

from scipy.integrate import quad
from scipy.special import expit

import time
from sympy import symbols,Eq,solve
# import warnings
# warnings.filterwarnings("ignore")

t0= time.perf_counter()

directory = r'C:\Users\gyanj\Documents\GADGET BACKUP\University\5th Year\Thesis\Python Simul\ODwyer\Plots'
os.chdir(directory) 

c = 3e8 #speed of light,m/s
q = 1.602e-19 # charge of electron,C
h = 6.626e-34/q #Planck's Constant,eVs
k = 8.617e-5 # Boltzmann's Constant,eVK^-1
stefan = 5.67e-8 #Stefan-Boltzmann's Constant,Wm^-2K^-4
T_C = 300 #Cold Reservoir Temperature,K
T_S = 6000 #Sun Temperature,K
Omega = np.pi #Absorption/Emission Solid Angle,sr
A = 1e-4 #Absorber Area,m^2

points = 21 # Number of plotting points
num_T = 300 #Number of temperatures to iterate through
Temperatures = np.linspace(T_C,T_S,num_T) # array of temperatures

E_u = 1 #Average electrochemical potential of system,eV
V = np.linspace(0,1,points) #V applied symetrically across device

max_lim = np.inf# integral upper limit

W = [1e-2] #Transmission function width
N = [1e9,1e10,1e12] #Number of contacts

#Following block used for progress bar (not relevant to calculations)
global total 
total = len(W)*len(N)*(points)*len(Temperatures)
progress = 0
counter = 0
full_time = 0

#Object containing all relevant parameters
class param:
    def __init__(self,TH,I,P,n,Qrad,Qabs):
        self.TH = TH #Hot reservoir/Absorber Temperature,K
        self.I = I # Current,A/m^2
        self.P = P #Power,W/m^2
        self.n = n #Efficiency
        self.Qrad = Qrad #net incoming energy flow due to radiation
        self.Qabs = Qabs #net heat current flowing out of the hot absorber reservoir

Data = np.empty([len(W),len(N),points],dtype = object) #Contain all param objects

datafile = 'ODwyer.dat'
fout = open(datafile,'w')
fout.write('')
fout.close()

for i in range(len(W)):
    for j in range(len(N)):
        for x in range(points):
            Data[i][j][x] = param(0,0)

# Function Paramaters calculates Qrad,Qabs and I for a given T_H,u_H,u_C,N_contact,w,voltage
def Parameters (T_H,voltage):
    eqn1 = lambda E: ((E)**3/(np.exp(E/(k*T_S))-1)-(E)**3/(np.exp(E/(k*T_H))-1))
    Qrad = ((2*Omega*A*q)/((h**3)*(c**2)))*quad(eqn1,max_lim)[0]
    eqn2 = lambda E:(E-u_H)*(expit(-(E-u_H)/(k*T_H))-expit(-(E-u_C)/(k*T_C)))*(np.exp(-(E-E_u/2)**2/(w)))
    Qabs = ((4*N_contact*q)/h)*quad(eqn2,max_lim)[0]
    if Qabs < 0:
        Qabs = np.inf
    error = abs(Qrad-Qabs)
    eqn3 = lambda E:(expit(-(E-u_H)/(k*T_H))-expit(-(E-u_C)/(k*T_C)))*(np.exp(-(E-E_u/2)**2/(w)))
    I = -((2*N_contact*q)/h)*quad(eqn3,max_lim)[0]/A
    fout = open(datafile,'a')
    fout.write('%.2e\t%.2e\t%.1f\t%.2f\t%.2e\t%.2e\n'%(w,T_H,voltage,Qabs))
    fout.close()
    return error,Qabs

#Progress bar for simulation time (not relevant for calculations)
def progressbar(progress):
   if (progress >= 0.01):
        t1 = time.perf_counter() - t0
        full_time = t1*1/progress*100
        timeleft = full_time-t1
        if timeleft >= 3600:
            timelefthrs = int(round(timeleft/3600,0))
            timeleftmins = int((timeleft-timelefthrs*3600)%60)
            print('\rSimulation Progress: %.2f%%\t Estimated Time Left: %dh %dm  '%(progress,timelefthrs,timeleftmins),end='')
        elif timeleft >= 60 and timeleft <3600: # in mins
            timeleftmins = int(round(timeleft/60,0))
            timeleftsecs = int((timeleft-timeleftmins*60)%60)
            print('\rSimulation Progress: %.2f%%\t Estimated Time Left: %dm %ds  '%(progress,timeleftmins,timeleftsecs),end='')
        else:
            print('\rSimulation Progress: %.2f%%\t Estimated Time Left: %ds  '%(progress,timeleft),end='')
   else:
        print('\rSimulation Progress: %.2f%%'%(progress),end='') 

def Odwyer(index,counter):
    for j in range(len(N)):
        for i in range(points): #per V
            u_H = E_u+V[i]/2 #Hot absorber electrochemical potential,eV
            u_C = E_u-V[i]/2 #Cold Reservoir electrochemical potential,eV            
            error = np.inf #initialise error between Qrad and Qabs as inf
            for x in range(len(Temperatures)):
                temperature = Temperatures[x]
                diff,Qabs= Parameters(Temperatures[x],N[j],W[index],V[i])
                if diff <= error: #if difference between Qabs and Qrad is smaller than previous error,use this Temperature[x]
                    Data[index][j][i].TH = temperature
                    Data[index][j][i].Qrad = Qrad
                    Data[index][j][i].Qabs = Qabs
                    Data[index][j][i].I = I
                    Data[index][j][i].P = I*V[i]
                    Data[index][j][i].n = I*V[i]/(stefan*(T_S**4))                    
                    error = abs(diff)
                counter += 1
                progress = counter/total*100
                progressbar(progress)
    
    #Plotting        
    
    fig,axs= plt.subplots(2,2,constrained_layout=True)
    
    ax1 = axs[0,0]
    ax2 = axs[0,1]
    ax3 = axs[1,0]
    ax4 = axs[1,1]
    
    for i in range(2):
        for j in range(2):
            axs[i,j].set_xlim(0,1)            
            axs[i,j].xaxis.set_major_locator(ticker.MultipleLocator(0.5))            
            axs[i,j].set_xlabel("Voltage (V)")
    
    ax1.set_ylim(0,T_S) 
    ax1.set_ylabel("TH (K)")
    ax1.yaxis.set_major_locator(ticker.MultipleLocator(2000))
    
    ax2.set_ylim(0,1e8) 
    ax2.set_ylabel("I (A/m^2)")
    ax2.yaxis.set_major_locator(ticker.MultipleLocator(2e7))
    
    ax3.set_ylim(0,1e8) 
    ax3.set_ylabel("Power (W/m^2)")
    ax3.yaxis.set_major_locator(ticker.MultipleLocator(2e7))
    
    ax4.set_ylim(0,1) 
    ax4.set_ylabel("Efficiency")
    ax4.yaxis.set_major_locator(ticker.MultipleLocator(0.2))
    
    TH = np.empty([len(N),points])
    I = np.empty([len(N),points])
    P = np.empty([len(N),points])
    n = np.empty([len(N),points])
    
    for j in range(len(N)):
        for x in range(points):
            TH[j][x] = Data[index][j][x].TH
            I[j][x] = Data[index][j][x].I
            P[j][x] = Data[index][j][x].P
            n[j][x] = Data[index][j][x].n
            
    #Wurfel's Solution
    TH_W = []
    I_W = []
    P_W = []
    n_W = []
    
    for x in range(points):
        if V[x] == E_u:
            TH_wurfel = 1e20
        else:
           TH_wurfel = T_C/(1-V[x]/E_u)
        TH_W.append(TH_wurfel)
        Iwurfel = (stefan)/(E_u)*(T_S**4-TH_wurfel**4)
        Pwurfel = stefan*(T_S**4-TH_wurfel**4)*(1-T_C/TH_wurfel)
        nwurfel = (T_S**4-TH_wurfel**4)/(T_S**4)*(1-T_C/TH_wurfel)
        I_W.append(Iwurfel)
        P_W.append(Pwurfel) 
        n_W.append(nwurfel)
    
    linestyles = ['--','-','-.']
    
    for j in range(len(N)):
        for x in range(points):
            if TH[j][x] == T_S:
                TH[j][x] = 1e8
    
        
    for i in range(len(N)):
        ax1.plot(V,TH[i],label='N = %.0e'%N[i],color = 'black',linestyle = linestyles[i],linewidth = 1)
        ax2.plot(V,I[i],linewidth = 1)
        ax3.plot(V,P[i],linewidth = 1)
        ax4.plot(V,n[i],linewidth = 1)
        
    ax1.plot(V,TH_W,label='Wurfel',linewidth = 3)
    ax2.plot(V,I_W,linewidth = 3)
    ax3.plot(V,P_W,linewidth = 3)
    ax4.plot(V,n_W,linewidth = 3)
    
    fig.suptitle('w = %.0e eV' % W[index])
    ax1.legend(loc='upper right',fontsize = 8)
    ax2.legend(loc='upper right',fontsize = 8)
    ax3.legend(loc='upper right',fontsize = 8)
    ax4.legend(loc='upper right',fontsize = 8)
    
    #Saving figure
    
    fig.savefig('w = %.0e eV,pp = %d,num_T = %d.jpg' %(W[index],points,num_T),dpi=800)
    
    return counter

for x in range(len(W)):
    counter = Odwyer(x,counter)
    
# Printing out object values

for x in range(len(W)):
    for j in range(len(N)):
        print('Parameters for W = %0.e,N = %.0e'%(W[x],N[j]))
        for i in range(points):
            print('w = %.0e\tV = %.2f\tTH = %.0f\tQrad = %.2e\tQabs = %.2e\tI = %.2e'%(W[x],V[i],Data[x][j][i].TH,Data[x][j][i].Qrad,Data[x][j][i].Qabs,Data[x][j][i].I))

print('\nComplete!')

我的尝试

我尝试将积分的上限从 inf 更改为较低的值,尽管它删除了值 ~Overflow Post 等溢出的解决方案,但无济于事。这是我的第一篇文章,所以如果您需要我提供更多信息来解决我的问题,请随时告诉我!

解决方法

这是一个快速而肮脏的 stdlib(没有 numpy)脚本,它与 WolframAlpha 的答案很接近:

from math import exp,pi

C1 = 8.617e-5 * 6000
C2 = 8.617e-5 * 1448

def f(x):
    denom1 = exp(x / C1)
    denom2 = exp(x / C2)
    # did some algebra
    difference = (denom2 - denom1) / (denom1 - 1) / (denom2 - 1)
    return x ** 3 * difference

bins = 10_000
endpoint = 10

total = 0.0
for i in range(1,bins+1):
    x = i * endpoint / bins
    total += f(x)
# account for widths
total *= (endpoint / bins)

scaled = float(total) * 2 * pi * 1e-4 / (4.14e-15)**3 / (3e8)**2

print(scaled)
# 4.549838698077388e+22

问题的一部分(我猜,不确定)是 1/(a-1) - 1/(b-1) 对于接近 1 的 a 和 b 会非常不精确,所以你可以做一些代数来尝试解决这个问题,并使它(b-a)/(a-1)/(b-1)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res