python: ValueError: math domain error

Python 错误 ValueError 解析,实际错误实例详解 (二) 本篇文章我们继续ValueError错误实例分析。通过几个实际的实例来看一下ValueError错误,并给出解决方案。大家在以后的编码中可以举一反三,从而有效的避免此类ValueError错误。上面我们又通过三个实例来介绍了ValueError的情况。我们给出了原因以及解决的方案。至此我们的ValueError系列就暂时告一段落了。在后面的Python旅程中,我会分享更多的其他的关于 Python 的错误示例,希望大家在编码的过程中可以作为一个参考,从而避免一些没有必要的坑,专注于自己的想法的实现。 阅读详情

import math

tmp3 = math.log((1/3), 2)#

print  tmp3

错误提示:

File "/self/_UDACity/pythonLearning/mathTest.py", line 28, in <module>
    tmp3 = math.log((1/3), 2)#

ValueError: math domain error


意思:该操作在数学中不可执行;  why? 1/3 = 是整形相除,所以=0。对0取对数是不被允许的, 3/0 也不行,对-3开平方也不行,等等了

【两个整数的除法,为了保证类型一致性,仍旧是整数,所以是整除。】 


所以: tmp3 = math.log((1/3.0),2)# OK


或者 可以这样

tmp2 = math.log(Fraction(1,3),2) #OK
print  tmp2
但是:  Fraction(1,3) != 1/3 


【Python】绘图时报错ValueError: Invalid RGBA argument: (0.0, 0.5, 0.0, array([[0.42116073]])) 通常不会报出这种错误,但还是有奇人能搞出来。这种错误通过断点调试就可以发现错误 在利用Python进行绘图时可能报出这种错误。 Traceback (most recent call last): File "E:\Anaconda3\envs\python27\Lib\lib-tk\Tkinter.py", line 1542, in __call__ return self.func(*args) File "E:\Anaconda3\envs\python27\lib\site-packages\matplotlib\backends\_backend_tk.py", l 立即下载

相关推荐

VLSI数字信号处理系统——第九章滤波器和变换中的算法强度缩减

[课程学习] VLSI数字信号处理系统——第九章滤波器和变换中的算法强度缩减

夏风喃喃的博客 1615

【20211115】【Python】ValueError: math domain error 报错原因及解决办法

这个问题源于工作中编写的一个功率值转 dB 值的函数,函数输入存在 0 值,而 0 取对数是无意义的! 一、报错原因 Python 中报错 “math domain error” 通常是由于某些操作不符合数学定义,如:对非正数取对数、对负数开方等等。 二、解决办法 把 0 替换成一个很小的正数,该问题解决~ 三、举个栗子 import math # 功率值转dB值 def fun_pow2db(data_pow, n_dim): ...

诗小葵的博客 3万+

手把手教你用Chrome DevTools逆向分析抖音a_bogus参数(附完整日志插桩方法)

本文详细介绍了如何使用Chrome DevTools逆向分析抖音a_bogus参数的生成逻辑,包括XHR断点定位、日志插桩追踪和加密核心逻辑解析。通过实战案例,帮助开发者掌握逆向工程技巧,应对抖音接口的动态加密变化,特别适合研究dy接口和a_bogus参数的技术人员。

weixin_27741699的博客 800

python | 报错ValueError: math domain error

第一种情况: import math t = math.pow(-3,(0.2)) python规定:不能对负数开方,即使是奇数次方 解决方法: t = math.pow(abs(-3),(0.2)) * (-1) if -3<0 else 1 第二种情况: import math t = math.log((1/3), 2) print t 错误提示: 报错行:t = math.log((1//3), 2) ValueError: math domain error 意思.

黄佳俊的博客 2万+

在 CentOS Stream 10 上搭建 Kubernetes 集群并支持开发调试与日志查看

搭建 Kubernetes 集群的每个步骤详细的文档。

灵犀物润 1650

别再为PT100测温发愁了!手把手教你用ADS1247+STM32搞定高精度温度采集(附完整代码)

本文详细介绍了如何使用ADS1247与STM32构建高精度PT100测温系统,涵盖硬件设计、SPI配置、温度计算及调试技巧。通过24位ADC和内置PGA,实现0.1℃级精度,适用于工业自动化和医疗设备。附完整代码和常见问题解决方案,助你快速掌握高精度温度采集技术。

weixin_42524703的博客 347

【已解决】Python ValueError: math domain error 详解

【已解决】Python ValueError: math domain error 详解

我是 二川兄,对Web开发、GIS开发、3D模型、机器学习、面试技巧等方面都有一些涉猎~ 欢迎您加入技术交流圈!你可以在我的文章末尾找到我~ 6994

高光谱目标检测底层逻辑:假设检验、SNR与光谱角度理论解析

高光谱目标检测在遥感应用中常被视作光谱匹配问题,但其本质是统计判决。从假设检验的框架出发,每个像元都需要在目标与背景之间做出二元判断,Neyman-Pearson准则为不依赖先验概率的最优判决提供了依据。而检测性能的上限由信噪比决定,信噪比直接影响目标与背景分布的重叠程度。在高光谱场景中,光谱角度作为方向型特征,对光照和尺度变化具有天然鲁棒性,成为区分光谱形状差异的有效度量。结合工程实践,从建模、信噪比估算到特征选择,再到检测器设计,这一套底层逻辑能帮助我们理解为何不同算法在不同数据上效果差异巨大。本文围绕

weixin_29034963的博客 297

【Python】ValueError: math domain error 报错原因及解决办法

Python 中报错 “math domain error” 通常是由于某些操作不符合数学定义,如:除于了0。在可能出现0的地方,加上一个,或者减去一个很小的数。

abc1599620的博客 1713

图像紫边消除(depurple)

对图像紫边形成原因、消除方法进行了介绍。

沧海一升的博客 7571

【实战】LLaMA-Factory 如何做 LLM 的多轮对话微调

LLaMA-Factory 作为一个广受欢迎、易于使用的 LLM 微调框架,为开发者提供了便捷的途径来针对特定任务(包括多轮对话)优化模型。本文将深入探讨 LLaMA-Factory 如何支持多轮对话微调,涵盖其基本概念、数据准备、核心机制、评估方法等。简单来说,多轮对话是指包含两个或更多轮次(Turn)的交互过程,其中每一轮通常包含用户的一个输入和模型的一个输出。后续轮次的回应通常依赖于前面轮次的对话内容。模型需要理解并记忆对话历史。

kakaZhui的博客 1315

python报错ValueError: math domain error

这里的原因市1-a被认为可能是负的了,但是实际上a的取值范围是0-1,1-a不可能是负的。这里应该是math包里面存在的bug吧,如果换成np.log()函数就不会有上面的问题了。引入numpy包,将math.log()换成了np.log()。1.在不确定正负的情况下,还可以加入abs(),强制转换成正数。

m0_67248857的博客 403

遗传算法(Genetic Algorithm)详解与实现

遗传算法(Genetic Algorithm, GA)是受自然进化原理启发的一系列搜索算法。通过模仿自然选择和繁殖的过程,遗传算法可以为涉及搜索、优化和学习的各种问题提供高质量的解决方案。同时,它们类似于自然进化,因此遗传算法可以克服传统搜索和优化算法遇到的一些障碍,尤其是对于具有大量参数和复杂数学表示形式的问题。

盼小辉丶的博客 24万+

Python ValueError: math domain error解决方法

ValueError: math domain error 原文 math.sqrt() 原因是根号内为负数导致的计算错误,

qq_43511299的博客 7194

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

python: ValueError: math domain error

log()改用 math.log()或者np.log()

weixin_37260876的博客 5781

【ValueError: math domain error】

写python程序时,出现错误: ValueError: math domain error 原因:某些操作不符合数学定义,如对负数取对数,对负数开平方。

hefei_cyp的博客 9万+

python,math函数中的sqrt数学函数出现这个报错ValueError: math domain error

出现该报错的原因: 1如 对负数开平方,该操作就不符合数学定义 实例

lovelygirlyuzhu的博客 4269

【Python_Error collection】

Python_Error collection python: ValueError: math domain error solution:math.log()或者np.log()(最好还是np.log吧,math还是有问题)

HollrayChan的博客 1055

解决 ValueError: math domain error

看到原因了吧,给一个负数开平方!

dqchouyang的专栏 708

math.asin_带有Python示例的math.asin()方法

math.asin Python math.asin()方法 (Python math.asin() method) math.asin() method is a library method of math module, it is used to get the arc sine, it accepts a number between -1 to 1 and returns the ar...

cumubi7552的博客 1759

经纬度计算球面距离,ValueError: math domain error错误

测试

Nafisa06的博客 992

Python数学三剑客:math、fractions与numpy分工解析

在Python数值计算中,math模块提供标准单点数学函数,fractions模块实现有理数精确表达,numpy则支撑大规模向量化运算——三者构成从精度保障、确定性计算到高性能处理的完整技术栈。math解决浮点比较、取整、对数等基础运算的可靠性问题;fractions通过分子分母整数存储规避IEEE 754浮点误差,是金融、教育等高精度场景的刚需;numpy依托ndarray和广播机制,将循环计算升维为内存级并行操作,成为科学计算生态基石。理解三者的边界与协同,是写出健壮、高效、可维护数学代码的关键。

weixin_30500473的博客 407

Python数学三剑客:math、fractions与numpy选型指南

在Python数值计算中,math模块提供标准浮点函数,fractions模块实现精确有理数运算,numpy则支撑大规模向量化计算——三者构成分层数学基础设施。理解其底层原理(如math的单值约束、fractions的整数分子分母机制、numpy的广播与内存连续性)是规避精度误差、性能瓶颈和类型错误的关键。技术价值体现在:math保障轻量确定性,fractions解决浮点漂移信任危机,numpy释放并行计算吞吐力。典型应用场景包括科学仿真、金融建模、教育系统与嵌入式脚本。当任务从单值计算升级为数组处理、从容

weixin_34417200的博客 654
上一篇: calculate and return the accuracy on the test data
zhglinux
博客等级 码龄18年 4粉丝 6原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址