- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要创建一个方法,当传递您想要区分的变量时,该方法必须以项的形式返回函数的偏导数。这是我的类,方法是区分:
package poly;
import java.util.ArrayList;
import java.util.TreeSet;
import util.Vector;
/** Implements an individual term in a polynomial. If 5x^2 + 3xy is a polynomial,
* it has two terms 5x^2 and 2xy, each of which would be represented by a different
* instance of this class.
*
* @author ssanner@mie.utoronto.ca
*
*/
public class Term {
// For term 2.1*x^4*y*z^2, the data members would take values as follows:
public double _coef; // = 2.1
public ArrayList<String> _vars; // = ["x", "y", "z"]
public ArrayList<Integer> _pows; // = [4, 1, 2]
/** This constructor has been implemented for you.
*
* @param coef -- sets the _coef member
*/
public Term(double coef) {
_coef = coef;
_vars = new ArrayList<String>();
_pows = new ArrayList<Integer>();
}
/** This constructor has been implemented for you -- it parses a term
* representation from a String into the format required by this class.
* You need two understand the following code.
*
* @param s -- String to parse
* @throws PolyException if s is malformed
*/
public Term(String s) throws PolyException {
if (s == null || s.trim().equals(""))
throw new PolyException("Empty Term, cannot read");
// Initialize this term
_coef = 1.0d; // Will multiply any constants by this
_vars = new ArrayList<String>();
_pows = new ArrayList<Integer>();
// You need to understand all lines of the following code
String[] factors = s.split("\\*");
for (String factor : factors) {
factor = factor.trim(); // Get rid of leading and trailing whitespace
try {
// If successful, multiplies in a constant (multiple constants in a product allowed)
_coef *= Double.parseDouble(factor);
} catch (NumberFormatException e) {
// If not a coefficient, must be a factor "<var>^<pow>"
// Must be a variable to a power -- parse the factor and add to list
int pow = 1; // If no power, defaults to 1
String[] var_pow = factor.split("\\^");
String var = var_pow[0];
if (var_pow.length == 2) {
try { // Second part must be exponent
pow = Integer.parseInt(var_pow[1]);
} catch (NumberFormatException f) {
throw new PolyException("ERROR: could not parse " + factor);
}
} else if (var_pow.length > 2)
throw new PolyException("ERROR: could not parse " + factor);
// Successfully parsed variable and power, add to list
if (_vars.contains(var))
throw new PolyException("ERROR: " + var + " appears twice in " + s);
_vars.add(var);
_pows.add(pow);
}
}
}
/** Produce a re-parseable representation of this Term as a String. This
* has been done for you.
*
*/
public String toString() {
// Using "+" to append Strings involves a lot of String copies since Strings are
// immutable. StringBuilder is much more efficient for append.
StringBuilder sb = new StringBuilder();
sb.append(String.format("%01.3f", _coef));
for (int i = 0; i < _vars.size(); i++) {
String var = _vars.get(i);
int pow = _pows.get(i);
sb.append("*" + var + (pow == 1 ? "" : "^" + pow));
}
return sb.toString();
}
/** Returns all of the variables used in this Term as a sorted set (TreeSet).
* This has been implemented for you, but you need to understand how it works
* since you'll write a similar method in Polynomial that uses this method.
*
* @return
*/
public TreeSet<String> getAllVars() {
// TreeSets are like HashSets but sorted alphabetically (lookup and insertion are
// a little less efficient than HashSets, but this won't matter for our sizes).
return new TreeSet<String>(_vars);
}
///////////////////////////////////////////////////////////////////////////////
// TODO: Your methods here! You should add some helper methods that facilitate
// the implementation of the methods below.
///////////////////////////////////////////////////////////////////////////////
/** If Term defines a function f(x,y) = 2xy^2 and assignments is { x=2.0 y=3.0 }
* then this method returns 36.0, which is the evaluation of f(2.0,3.0).
*
* @param assignments
* @return
* @throws PolyException
*
*
*/
public double coef(){
return _coef;
}
public Double var(int i){
return Double.parseDouble(_vars.get(i));
}
public ArrayList power(){
return _pows;
}
public double evaluate(Vector assignments) throws PolyException {
double evaluated = 0;
double sum = 0;
for(int i = 0; i < _vars.size(); i++){
sum += Math.pow(var(i), _pows.get(i));
}
evaluated *= sum;
return evaluated;
}
/** If Term defines a function f(.) then this method returns the **symbolic**
* partial derivative (which you can verify from calculus is still a Term):
*
* partial f(1.0,2.0) / partial var.
*
* Specifically, if Term defines a function f(x,y) = 2xy^2 and var = "x"
* then this method returns a **new** Term 2y^2 and if var = "y" then it
* instead returns a **new** Term 4xy.
*
* @param var
* @return partial derivative of this w.r.t. var as a new Term
*/
public Term differentiate(String var) {
// TODO: Should not return null!
return null;
}
}
最佳答案
我不确定如何调用区分方法,但区分相对简单的函数的方法示例可以如下完成...
请注意,此方法可以使用一些微调(它返回一个字符串而不是术语值),并且它没有考虑日志/触发函数等,但希望这是一个有用的开始。
public static void main(String args[]) {
String differentiated = differentiate("32x^2y^3", "x");
System.out.println(differentiated);
}
public static String differentiate(String function, String var) {
StringBuilder partialDerivative = new StringBuilder();
int indexOfVar = function.indexOf(var);
boolean coefficient = false;
String coefficientValue;
double coefficientAmount = 1;
StringBuilder powerValue = new StringBuilder();
StringBuilder variable = new StringBuilder();
double powerAmount;
StringBuilder otherVariables = new StringBuilder();
//ascertains whether a coefficient is present
int k = 0;
while (Character.isDigit(function.charAt(k))) {
coefficient = true;
if (k == 0) {
coefficientValue = Character.toString(function.charAt(k));
} else {
coefficientValue = function.substring(0, k+1);
}
coefficientAmount = Double.parseDouble(coefficientValue);
k++;
}
//checks for other variables that may also have polynomials
for (int i = 0; i <= function.length() - 1; i++) {
if (Character.isLetter(function.charAt(i)) && function.charAt(i) != var.charAt(0)) {
otherVariables.append(function.charAt(i));
if (i < function.length() - 1) {
if (function.charAt(i + 1) == '^') {
findPolynomial(function, i, otherVariables);
}
}
}
}
//works out if the var value has a polynomial and therefore times the coefficient by it and reduces it by one
if (function.charAt(indexOfVar + 1) == '^') {
findPolynomial(function, indexOfVar, powerValue);
powerAmount = Double.parseDouble(powerValue.toString().substring(1));
coefficientAmount *= powerAmount;
powerAmount -= 1;
powerValue.replace(1,powerValue.length(),Double.toString(powerAmount));
if(powerAmount != 1) {
variable.append(var).append(powerValue);
} else {
variable.append(var);
}
}
//include method for ln() or exponential functions
//include method for trig functions (sin() cos() etc)
if (coefficient) {
partialDerivative.append(coefficientAmount).append(otherVariables).append(variable);
} else {
partialDerivative.append(otherVariables).append(variable);
}
return partialDerivative.toString();
}
private static void findPolynomial(String function, int indexOfVar, StringBuilder powerValue) {
powerValue.append(function.charAt(indexOfVar + 1));
int j = indexOfVar + 2;
while (Character.isDigit(function.charAt(j))) {
powerValue.append(function.charAt(j));
if (j == function.length() - 1) {
break;
} else {
j++;
}
}
}
关于Java - 创建返回偏导数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58543590/
我有一个随时间变化的数据流。如何使用 C# 确定变化率? 自从上微积分课已经很长时间了,但现在是我第一次真正需要它(15 年来)。现在,当我搜索“衍生品”这个词时,我会得到金融方面的东西,以及我认为并
假设我有以下数据和命令: clc;clear; t = [0:0.1:1]; t_new = [0:0.01:1]; y = [1,2,1,3,2,2,4,5,6,1,0]; p = interp1(
假设我有以下数据和命令: clc;clear; t = [0:0.1:1]; t_new = [0:0.01:1]; y = [1,2,1,3,2,2,4,5,6,1,0]; p = interp1(
我曾经使用这个公式来计算每秒记录的信号的导数,然后对其应用滚动平均值。 df.rolling(rollingWindow, center=True).mean().diff(rollingWindow
通过这里的一些帮助,我想出了一个函数,它似乎将索贝尔导数应用于 X 方向的图像 F(x,y) = F(x+1,y) - F( x,y)我无法使用任何 OpenCV 函数,并且我需要 2D 输出数组比
对于神经网络库,我实现了一些激活函数和损失函数及其衍生物。它们可以任意组合,输出层的导数只是损失导数和激活导数的乘积。 但是,我未能独立于任何损失函数实现 Softmax 激活函数的导数。由于归一化,
我要在使用 ReLU 的神经网络上进行反向传播。 在我之前的一个项目中,我在一个使用 Sigmoid 激活函数的网络上做了,但现在我有点困惑,因为 ReLU 没有导数。 这是一个 image关于 we
我的任务是制作自己的 Sobel 方法,而不是使用 OpenCV 中的 cv::Sobel。我尝试实现我在 Programming techniques 找到的一个 但是,当我运行该程序时,cv::M
我愿意计算一个不完全明确的函数的 Frechet/Gateaux 导数,我的问题是:最有效的方法是什么?您会推荐我使用哪种语言? 准确地说,我的问题是我有一个函数,比如 F,它是多维函数对(即从 R^
我想使用 Flux.jl 绘制函数及其梯度和 Plots.jl using Flux.Tracker using Plots f(x::Float64) = 3x^2 + 2x + 1 df(x::F
我已将 ReLu 导数实现为: def relu_derivative(x): return (x>0)*np.ones(x.shape) 我也尝试过: def relu_derivativ
我几乎没有关于 Scharr 导数及其 OpenCV 实现的问题。 我对具有 (3X3) 内核的二阶图像导数感兴趣。我从 Sobel 二阶导数开始,它未能在图像中找到一些细线。看完this page底
import numpy as np def relu(z): return np.maximum(0,z) def d_relu(z): z[z>0]=1 z[z 0).as
你好,我用 C++ 创建了一个小的运动模拟。我想向学生展示 Euler、Runge-Kutta 和 MidPoint 方法之间的差异,有些 Material 点在撞击球体时会移动和反弹。 但是当我切换
或者,目标:如何以声明方式从 Nix 不稳定中获取单个包? 我是 NixOS 的新手,目前正在尝试安装比默认版本更新的 Consul 0.5.2我的 NixOS 版本(最新稳定版)。我正在尝试通过覆盖
我已经为此苦苦挣扎了很长一段时间。我想要的只是一个 torch.diff() 函数。然而,许多矩阵运算似乎并不容易与张量运算兼容。 我已经尝试了大量不同的 pytorch 操作组合,但它们都不起作用。
我试图了解如何在 Swift 中创建 Vector,因为当我执行 CGVectorMake() 时,它告诉我将 dx 和 dy(导数)作为 CGFloat 传递。如何创建仅包含该信息的向量(线)? 谁
我希望你能帮助我。 我正在使用 QT 并尝试对图像的边缘进行简单检测。但是当我启动时我的程序崩溃了 cv::GaussianBlur( src, src, cv::Size(3,3), 0, 0, c
我正在计算信号的一阶和二阶导数,然后进行绘图。我选择了在 SciPy(信号模块)中实现的 Savitzky-Golay 滤波器。我想知道是否需要缩放输出 - 在同一过滤器的 Matlab 实现中,指定
我是一名优秀的程序员,十分优秀!