category stringclasses 107
values | title stringlengths 15 179 | question_link stringlengths 59 147 | question_body stringlengths 53 33.8k | answer_html stringlengths 0 28.8k | __index_level_0__ int64 0 1.58k |
|---|---|---|---|---|---|
solve differential equations | MATLAB solve Ordinary Differential Equations | https://stackoverflow.com/questions/23962549/matlab-solve-ordinary-differential-equations | <p>How can I use matlab to solve the following Ordinary Differential Equations?</p>
<p><strong>x''/y = y''/x = -( x''y + 2x'y' + xy'')</strong></p>
<p>with two known points, such as t=0: x(0)= x0, y(0) = y0; t=1: x(1) = x1, y(1) = y1 ?
It doesn't need to be a complete formula if it is difficult. A numerical solution ... | <p>The following is the answer we finally get @Chriso: use matlab bvp4c function to solve this boundary value problem (Suppose the two boundry value conditions are: when t=0: x=1, y=3; when t=1, x=6, y=9. x is x(1), y is x(2) ):</p>
<pre><code>1. bc.m
function res = bc(ya,yb)
res = [ ya(1)-1; ya(2)-3; yb(1) - 6; yb(2)... | 234 |
solve differential equations | solving a pair of iterated differential equations | https://stackoverflow.com/questions/53525908/solving-a-pair-of-iterated-differential-equations | <p>Ive got a pair of differential equations that I've learnt how to solve:</p>
<blockquote>
<pre><code>dc/dt=r*c+c^2-c^3-b*c*u,
du/dt=-g*u+(b*c*u)/2,
</code></pre>
</blockquote>
<p>where r,b,g are constants (no assumption on r but b and g are positive). So my code to solve these are:</p>
<pre><code>from scipy.integ... | 235 | |
solve differential equations | Making an AbstractOdeSolver class library to solve differential equations numerically (c++) | https://stackoverflow.com/questions/46874293/making-an-abstractodesolver-class-library-to-solve-differential-equations-numeri | <p>I am trying to make and ode solver using c++ and numerical methods (euler, heun and runge kutta). first i made and abstract class for ode solving requirements then i made a separate class for each solver inheriting from the ABClass. there is no problem with the code excpet it works only with first order differential... | 236 | |
solve differential equations | Solving differential equations in Matlab | https://stackoverflow.com/questions/58895739/solving-differential-equations-in-matlab | <p>I need to solve these 2 differential equations simultaneously. </p>
<pre><code>dr^3/dt=(-3*D*Cs)/(ρ*r0^2 )*r*(1-C)
dC/dt=((D*4π*r0*N*(1-C)*r)-(Af*C))/V
</code></pre>
<p>Note: dr^3/dt is the derivative of r^3 with respect to t</p>
<p>The two equations resemble the change in particle radius (r) and concentration (... | <p>In the original form of the radius equation</p>
<pre><code>d(r^3)/dt = -3K*(r^3)^(1/3)*(1-C)
</code></pre>
<p>or the power-reduced one</p>
<pre><code>dr/dt = -K/r*(1-C) <==> d(r^2)/dt = -2K*(1-C)
</code></pre>
<p>you reach a singularity at the moment that the radius shrinks to zero like approximately <cod... | 237 |
solve differential equations | solving differential equation with step function | https://stackoverflow.com/questions/50471374/solving-differential-equation-with-step-function | <p>I am trying to solve this differential equation as part of my assignment. I am not able to understand on how can i put the condition for u in the code. In the code shown below, i arbitrarily provided </p>
<pre><code>u = 5.
2dx(t)dt=−x(t)+u(t)
5dy(t)dt=−y(t)+x(t)
u=2S(t−5)
x(0)=0
y(0)=0
</code></pre>
<p><cod... | <p>I do not know the SciPy Library very well, but regarding the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html" rel="nofollow noreferrer">example in the documentation</a> I would try something like this:</p>
<pre><code>def model(x, t, K, PT)
"""
The model consists of ... | 238 |
solve differential equations | matlab ODE45 solves Differential equations with two variables of same order | https://stackoverflow.com/questions/39295156/matlab-ode45-solves-differential-equations-with-two-variables-of-same-order | <p>I have a Differential equations such as below in matlab format </p>
<pre><code>syms x y m g r l J
% x,y are variables, the others are constant
1: 0.5*m*(r^2*x^2+l^2*(Dx-Dy)^2+2*r*l*Dx*(Dx-Dy)*cos(y))+0.5*J*(Dx-Dy)^2=m*g*
(l*sin(x-y)-r*(1-cos(x)));
2: J*(D2x-D2y)+l^2*(D2x-D2y)-r*l*(Dx)^2*sin(y)+r*l*D2x*cos(y... | <p>You need to solve for D2x and D2y to get an explicit ODE. Since there is only one equation for them, what you have is a DAE, differential-algebraic equation (system). </p>
<p>Thus you either employ a DAE solver or you have to compute the derivative of the first equation to get a second equation for the second deriv... | 239 |
solve differential equations | How to solve differential equations with silence period (using DifferentialEquations.jl)? | https://stackoverflow.com/questions/57578402/how-to-solve-differential-equations-with-silence-period-using-differentialequat | <p>I want to solve a differential equation that has some "silence period" (I'm not sure whether it has a formal name or not, it means during this period that the system is static and not controlled by the differential equation).</p>
<p>For example (see the figure), when a free-fall ball touches the ground, the callbac... | <p>The simplest way to do this is to set a parameter to zero using a <code>DiscreteCallback</code>, and having a second callback un-zero it. <a href="http://diffeq.sciml.ai/latest/features/callback_functions.html" rel="nofollow noreferrer">The callback handling page</a> describes in more detail how to define and use su... | 240 |
solve differential equations | Python error while solving complex coupled differential equations | https://stackoverflow.com/questions/34627594/python-error-while-solving-complex-coupled-differential-equations | <p>I'm trying to solve complex coupled differential equations as follows.</p>
<pre><code>import numpy as np
from scipy.integrate import complex_ode
def cae(z, A, params):
A1, A2, A3 = A
alpha, gamma, dbeta = params
dA = [
-0.5*alpha*A1 + 1j*gamma*(np.abs(A1)**2 + 2*np.abs(A2)**2 + 2*np.abs(A3)**... | 241 | |
solve differential equations | Solving an Involved Set of Coupled Differential Equations | https://stackoverflow.com/questions/66877010/solving-an-involved-set-of-coupled-differential-equations | <p>I am trying to solve a set of complicated differential equations in Python. These equations contain five functions (defined in the function 'ODEs' in the code below) that are functions of a variable n (greek name is eta--- I used n and eta interchangeably as variable names). These coupled differential equations cont... | 242 | |
solve differential equations | Solving 2nd order differential equations wrt this code | https://stackoverflow.com/questions/56349229/solving-2nd-order-differential-equations-wrt-this-code | <p>I cannot write the program which is solving 2nd order differential equation with respect to code I wrote for <strong>y'=y</strong></p>
<p>I know that I should write a program which turn a 2nd order differential equation into two ordinary differential equations but I don!t know how can I do in Python.</p>
<p>P.S. :... | <p>You can basically reformulate any scalar ODE (Ordinary Differential Equation) of order n in Cauchy form into an ODE of order 1. The only thing that you "pay" in this operation is that the second ODE's variables will be vectors instead of scalar functions.</p>
<p>Let me give you an example with an ODE of order 2. Su... | 243 |
solve differential equations | Julia Differential Equations Repositories | https://stackoverflow.com/questions/77032222/julia-differential-equations-repositories | <p>Is there a repository (or a web page) of all differential equations coded in DifferentialEquations.jl or at least ODE in OrdinaryDiffEq.jl?</p>
<p>If there are no repositories, are there other sources, university classes, etc. where Julia code is used to solve differential equations and is available?</p>
| <p>There are two ways to read this question. One is either looking for where the examples for the ODE definitions are contained, the other is looking for where the ODE solver codebases are found. I'll split this answer into the two possible interpretations.</p>
<h2>Where the ODE Problem Definition Examples are Found</h... | 244 |
solve differential equations | Solving system of differential equations | https://stackoverflow.com/questions/65201682/solving-system-of-differential-equations | <p>I am trying to solve RLC circuits using python.
When there are no Cs and Ls, after calculating i got to a linear system of equations which i solved using <code>numpy.linalg</code>, e.g :</p>
<pre><code>a + b = 1
a + c = 2
c - b = 1
</code></pre>
<p>But now i need to solve this with differential elements in it.<br />... | 245 | |
solve differential equations | Solving differential equations with discrete values in MATLAB using ode45 | https://stackoverflow.com/questions/64633010/solving-differential-equations-with-discrete-values-in-matlab-using-ode45 | <p>I have a differential equation-</p>
<pre><code>L'(x) = F1(x,L(x))
</code></pre>
<p>Using ode45, I have obtained the solution for L(x). I have an array of values for L(x) denoted by L_val. Using this solution, I intend to solve another differential equation.</p>
<pre><code>w'(x)=L(x)/x
</code></pre>
<p>How can I solv... | <p>Use the cumulative trapezoidal integration function:
<a href="https://fr.mathworks.com/help/matlab/ref/cumtrapz.html" rel="nofollow noreferrer">https://fr.mathworks.com/help/matlab/ref/cumtrapz.html</a></p>
<p>Alternatively, you may use other rules with a better accuracy (Simpson's rule, search in Matlab central for... | 246 |
solve differential equations | Solve differential equation using finite difference method | https://stackoverflow.com/questions/76059170/solve-differential-equation-using-finite-difference-method | <p>I am trying to solve a second order differential equation using finite difference method. In the following code I have a function to calculate the first derivative and the second derivative. I am creating a sparse matrix with one column and trying to solve it using <code>np.linalg</code>. However, the <code>f</code>... | 247 | |
solve differential equations | Problems using Python to solve coupled delay differential equations (DDEs) | https://stackoverflow.com/questions/19104131/problems-using-python-to-solve-coupled-delay-differential-equations-ddes | <p>I am trying to use <code>pydelay</code> library to solve a system of delay differential equations. I have followed <a href="http://pydelay.sourceforge.net/" rel="nofollow">instructions</a> to setup my model. However, I ran into some errors and really appreciate any suggestions.</p>
<p>Here is my code:</p>
<pre><co... | 248 | |
solve differential equations | A Python library for solving some integro-differential equations? | https://stackoverflow.com/questions/18841528/a-python-library-for-solving-some-integro-differential-equations | <p>I have <em>a huge set of <strong>coupled nonlinear integro-partial differential</strong> equations</em>. After a long while trying to simplify the equations and solve them at least semi-analytically I have come to conclude there has been left no way for me but an efficient numerical method. Finite element seems most... | 249 | |
solve differential equations | Solve a system of differential equations using Euler's method | https://stackoverflow.com/questions/29870245/solve-a-system-of-differential-equations-using-eulers-method | <p>I'm trying to solve a system of ordinary differential equations with Euler's method, but when I try to print velocity I get</p>
<pre><code>RuntimeWarning: overflow encountered in double_scalars
</code></pre>
<p>and instead of printing numbers I get <code>nan</code> (not a number). I think the problem might be when... | <p>In future it would be helpful if you included the full warning message in your question - it will contain the line where the problem occurs:</p>
<pre><code>tmp/untitled.py:15: RuntimeWarning: overflow encountered in double_scalars
return (g-((densaire*g)/densparticula)-((mu*18.0*v)/(cc*densparticula* (D**2.00)))... | 250 |
solve differential equations | solving system of differential equations with odient | https://stackoverflow.com/questions/78783282/solving-system-of-differential-equations-with-odient | <p>I tried to solve system of two differential equations using <code>scipy.integrate.odient</code>.
The results are far from my expectations as one can see from the plots I attached below.</p>
<p>This is the system of ODEs:</p>
<p><img src="https://i.sstatic.net/KIuEvcGy.png" alt="" /></p>
<p>where alpha and beth fun... | 251 | |
solve differential equations | Solving a large system of coupled differential equations using RK4 | https://stackoverflow.com/questions/69273973/solving-a-large-system-of-coupled-differential-equations-using-rk4 | <p>I want to solve a system of differential equations using the RK4 method, like given below. <a href="https://i.sstatic.net/RJhmw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/RJhmw.png" alt="enter image description here" /></a></p>
<p>So for this case, I've to solve 3 differential equations-</p>
<p>d... | 252 | |
solve differential equations | Solving differential equations in realtime in a webapp | https://stackoverflow.com/questions/16735309/solving-differential-equations-in-realtime-in-a-webapp | <p>Is this undoable? Say I have a complex system of differential equations that I want to have a live user-based input to them and then I want to plot the results in real time. It doesn't seem like javascript has the precision or mathematical dexterity. My initial thought was to use python with scipy for ode solving... | 253 | |
solve differential equations | Solving differential equations with ode solvers and finite difference in Matlab | https://stackoverflow.com/questions/79252262/solving-differential-equations-with-ode-solvers-and-finite-difference-in-matlab | <p>I have implemented following equations both with the Matlab own ODE solvers and with a very simple finite difference scheme. The latter works properly, while the ODE code does not produce suitable solutions. What I am doing wrong? These are a set of coupled implicit differential equations.</p>
<pre><code> % Defin... | 254 | |
solve differential equations | python: Initial condition in solving differential equation | https://stackoverflow.com/questions/49964702/python-initial-condition-in-solving-differential-equation | <p>I want to solve this differential equation:
y′′+2y′+2y=cos(2x) with initial conditions:</p>
<ol>
<li><p>y(1)=2,y′(2)=0.5</p></li>
<li><p>y′(1)=1,y′(2)=0.8</p></li>
<li><p>y(1)=0,y(2)=1</p></li>
</ol>
<p>and it's code is:</p>
<pre><code>import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot... | <p>Your initial conditions are not, as they give values at two different points. These are all boundary conditions.</p>
<pre class="lang-py prettyprint-override"><code>def bc1(u1,u2): return [u1[0]-2.0,u2[1]-0.5]
def bc2(u1,u2): return [u1[1]-1.0,u2[1]-0.8]
def bc3(u1,u2): return [u1[0]-0.0,u2[0]-1.0]
</code></pre>
<p>... | 255 |
solve differential equations | How to solve this system of IVP differential equations | https://stackoverflow.com/questions/61442582/how-to-solve-this-system-of-ivp-differential-equations | <p>I have a system of differential equations like this</p>
<p><code>
dy/dt = f(t,y,y1,y2,....,yn,x),
dy1/dt = f(t,y,y1,y2,..yn,x),
.
.
.
dyn/dt = f(t,y,y1,y2,..yn,x),
x(t) = f(t,y1,y2,...yn,x)
</code></p>
<p>And I have the values y_i(0),x(0)
If I had dx/dt then simply using scipy.integrate IVP I could solve this. I ... | <p>No problem, define </p>
<pre class="lang-py prettyprint-override"><code>def derivatives(t,y):
xt = func_x(t,y);
dy = func_y(t,y,xt)
return dy
</code></pre>
<p>where <code>func_y</code> takes scalar (<code>t</code>,<code>xt</code>) and vector (<code>y</code>) arguments and returns a vector of the same s... | 256 |
solve differential equations | Solving System of Differential Equations using SciPy | https://stackoverflow.com/questions/30566994/solving-system-of-differential-equations-using-scipy | <p>I'm trying to solve the following system of differential equations using scipy:</p>
<pre><code>q1''(t) + M/L1 * q2''(t) + R1/L1 * q1'(t) + 1/(C1 * L1) * q1(t) = 0
q2''(t) + M/L2 * q1''(t) + R2/L2 * q2'(t) + 1/(C2 * L2) * q2(t) = 0
</code></pre>
<p>I'm trying to use scipy.integrate.odeint to obtain a numerical sol... | <p>You have two coupled second order equations. When this system is converted to a system of first order equations, there will be four equations, not six.</p>
<p>Do a little algebra by hand to solve for the vector [q1''(t), q2''(t)] in terms of q1(t), q1'(t), q2(t) and q2'(t). (For example, you can use that fact the ... | 257 |
solve differential equations | I would like to solve a system of network-based differential equations using python 3.6 | https://stackoverflow.com/questions/57447343/i-would-like-to-solve-a-system-of-network-based-differential-equations-using-pyt | <p>I would like to solve a system of network-based differential equations using python 3.6. The system of equations is as follows:</p>
<pre><code>dx_i/dt = omega_i - epsilon_i * y_i * x_i - mu_i * x_i,
dy_i/dt = epsilon_i * y_i * x_i - zeta_i * y_i - rho_i * y_i * z_i,
dv_i/dt = c_i * y_i - gamma_i * v_i + \sum_{... | <p>Your translation of the model into code has index problems. You addressed this once in the sum calculation, but then never again. To help with that, define helper functions</p>
<pre class="lang-py prettyprint-override"><code>def X(i): return y(4*i)
def Y(i): return y(4*i+1)
def V(i): return y(4*i+2)
def Z(i): retur... | 258 |
solve differential equations | Solving differential equations in two different domains using the bvp solver in python | https://stackoverflow.com/questions/62016035/solving-differential-equations-in-two-different-domains-using-the-bvp-solver-in | <p>I am trying to solve the following set of coupled differential equations ( variables are p,n and psi) using the bvp solver in python :-</p>
<pre><code>1. d2n/dx2-(d2psi/dx2)n-(dpsi/dx)(dn/dx)=k1 in domain 1
2. d2p/dx2+(d2psi/dx2)p+(dpsi/dx)(dp/dx)=k2 in domain 1
3. d2psi/dx2= k*(p-n) in domain 1
4. d2psi/dx2= 0 in ... | 259 | |
solve differential equations | Sympy: solve a differential equation | https://stackoverflow.com/questions/33340217/sympy-solve-a-differential-equation | <p>I want to find an elegant way of solving the following differential equation:</p>
<pre><code>from sympy import *
init_printing()
M, phi, t, r = symbols('M phi t r')
eq = Eq(-M * phi(t).diff(t), Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t,t))
</code></pre>
<p><a href="https://i.sstatic.net/0l4ID.pn... | <p>Ideally <code>dsolve()</code> would be able to solve the equation directly, but it doesn't know how (it needs to learn that it can factor an equation and solve the factors independently). I opened an <a href="https://github.com/sympy/sympy/issues/10043" rel="nofollow">issue</a> for it. </p>
<p>My only other sugges... | 260 |
solve differential equations | Solve differential equation with two variables in Simulink | https://stackoverflow.com/questions/42350080/solve-differential-equation-with-two-variables-in-simulink | <p>I have a differential equation of the form:</p>
<pre><code>xs'' = rhs * theta
</code></pre>
<p>to solve in Simulink, where <strong>xs</strong> and <strong>theta</strong> are variables and <strong>rhs</strong> is a numerical constant. So far, I've got this: <a href="https://i.sstatic.net/EzVLY.png" rel="nofollow no... | <p>This works as expected:</p>
<p><a href="https://i.sstatic.net/mWDcZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mWDcZ.png" alt="enter image description here"></a></p>
<p>Thanks to @Ander Biguri!</p>
| 261 |
solve differential equations | How to solve this system of differential equations in matlab? | https://stackoverflow.com/questions/57548600/how-to-solve-this-system-of-differential-equations-in-matlab | <p>My task is to model a certain physical problem and use matlab to solve it's differential equations. I made the model but it seems far more complex than what I've learned so far so I have no idea how to solve this.</p>
<p>The black color means it's a constant</p>
<p><img src="https://i.sstatic.net/aRzfw.jpg" alt="T... | <p><strong>I assume that by "solve" you seek a closed form solution of the form x(t) = ..., z(t) = ...</strong> Unforunately, it's very likely you cannot solve this system of differential equations. Only very specific <em>canonical</em> systems actually have a closed-form solution, and they are the most simple (few ter... | 262 |
solve differential equations | Solving differential equations in a loop with different parameters each time R | https://stackoverflow.com/questions/36941968/solving-differential-equations-in-a-loop-with-different-parameters-each-time-r | <p>I think, this should be simple.
I'm solving numerically a set of differential equations in R. When I do it one it is fine. However I need to test the set of differential equations for several groups of parameters, thus I am using a loop. The problem is that for all the set of parameters it shows the same values, whi... | 263 | |
solve differential equations | Solving nonlinear system of differential equations in wolfram mathematica | https://stackoverflow.com/questions/37351824/solving-nonlinear-system-of-differential-equations-in-wolfram-mathematica | <p>How can I solve nonlinear system of differential equations and get plot for this solution? The system is without initial conditions. For example,</p>
<p>x'= (x + y)^2 - 1
y'= -y^2 - x + 1</p>
| <p><a href="https://reference.wolfram.com/language/tutorial/DSolveIntroduction.html" rel="nofollow">Introduction to Differential Equation Solving with DSolve</a></p>
<p>See also <a href="https://reference.wolfram.com/language/tutorial/DSolveSettingUpTheProblem.html" rel="nofollow">Setting Up the Problem</a> scroll do... | 264 |
solve differential equations | syntax for solving system of differential equations in sympy | https://stackoverflow.com/questions/26172733/syntax-for-solving-system-of-differential-equations-in-sympy | <p>I am new to sympy and in the process of learning it. I was browsing through the documentation and questions in stack exchange regarding symbolically solving a system of differential equations with initial conditions using sympy. </p>
<p>I have a simple system of ODE-s</p>
<pre><code>( dV/dt ) = -( 1 / RC ) * ( V... | <p>System of ODEs support is only in the development version of SymPy. It will be added in 0.7.6. The syntax would be</p>
<pre><code>V, I = symbols("V I", cls=Function)
RC, t, C, Vs, L, R1, V0, I0 = symbols("RC t C Vs L R1 V0 I0")
system = [Eq(V(t).diff(t), -1/RC*V(t) + I(t)/C), Eq(I(t).diff(t), -R1/L*I(t) - 1/L*V(t) ... | 265 |
solve differential equations | Solving a system of first order differential equations and second order differential equations (Non-linear) | https://stackoverflow.com/questions/64372007/solving-a-system-of-first-order-differential-equations-and-second-order-differen | <p><strong>The problem</strong></p>
<p>I currently have a system of four equations. Two are second-order differential equations and two are first-order differential equations:</p>
<p><a href="https://i.sstatic.net/IQtr6.png" rel="nofollow noreferrer">Four equations</a></p>
<p>The initial conditions are:</p>
<pre><code>... | <p>Scipy has a <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.RK45.html" rel="nofollow noreferrer">Runge Kutta solver</a>. First, you have to transform your ODEs to first order system (you can always do that by setting z=y') and then try the RK solver.</p>
| 266 |
solve differential equations | Using a forloop to solve coupled differential equations in python | https://stackoverflow.com/questions/66361935/using-a-forloop-to-solve-coupled-differential-equations-in-python | <p>I am trying to solve a set of differential equations, but I have been having difficulty making this work. My differential equations contain an "i" subscript that represents numbers from 1 to n. I tried implementing a forloop as follows, but I have been getting this index error (the error message is below).... | <p>It is nice that you provide the standard solver with a vectorized ODE function for multi-point evalutions. But the default method is the explicit RK45, and explicit methods do not use Jacobi matrices. So there is no need for multi-point evaluations for difference quotients for the partial derivatives.</p>
<p>In esse... | 267 |
solve differential equations | solving a system of 6 differential equations by ODE45 in matlab | https://stackoverflow.com/questions/21588348/solving-a-system-of-6-differential-equations-by-ode45-in-matlab | <p>I am trying to solve a system of 6 differential equations using matlab. I created a set of 6 differential equations as follows in a function m file named as Untitled.m</p>
<pre><code>function ydot=Untitled(z,y)
ydot = zeros(6,1);
%y(1)=A
%y(2)=B
%y(3)=C
%y(4)=D
%y(5)=P
y(6)=T
A=0.50265
k11=(333/106.7)*1.15*1000*ex... | <p>Search for <code>)(</code> in your code, it's syntactically not allowed. Probably you missed a <code>*</code> in between.</p>
| 268 |
solve differential equations | Why isn't ode in R solving easy differential equations? | https://stackoverflow.com/questions/72897940/why-isnt-ode-in-r-solving-easy-differential-equations | <p>I want to use deSolve to solve coupled partial differential equations, and am trying to get used to the package by solving easy differential equations with ode. I know the solution to y' = sqrt(1-y^2) is sin(t + c), so I tested it with the starting conditions y(0) = 0 and y(0) = 1, expecting to get sin(t) and sin(t ... | <p>This is as expected, the right side <code>sqrt(1-y^2)</code> is always positive on the domain with value zero at <code>y=1</code>, so solutions are increasing to the constant solution <code>y=1</code>. As the right side is not Lipschitz there, numerical solvers might get a problem when reaching close to that value a... | 269 |
solve differential equations | Fortran or C and f2py to solve differential equations | https://stackoverflow.com/questions/33988654/fortran-or-c-and-f2py-to-solve-differential-equations | <p>This is more of a design question. I am involved with a project that requires us to solve a bunch of first order differential equations. I know the python has modules to this and we have been using those functions.</p>
<p>However, we need the integrator to be fast, so we want to use adaptive step sizes and test s... | <p>I'm not familiar with f2py, but have you considered trying <a href="http://docs.cython.org/" rel="nofollow">Cython</a> first? If you're not familiar with it, it lets you write code in a superset of the standard Python language, and then it translates that into C code which is then compiled. If your code is mostly lo... | 270 |
solve differential equations | Solving coupled nonlinear differential equations | https://stackoverflow.com/questions/47231292/solving-coupled-nonlinear-differential-equations | <p>I have a differential equation that is as follows:</p>
<pre><code>%d/dt [x;y] = [m11 m12;m11 m12][x;y]
mat = @(t) sin(cos(w*t))
m11 = mat(t) + 5 ;
m12 = 5;
m21 = -m12 ;
m22 = -m11 ;
</code></pre>
<p>So I have that my matrix is specifically dependent on t. For some reason, I am having a super difficult time solvi... | <p>I'm assuming you're running this within a script, which means that your function <code>ddt</code> is a <a href="https://www.mathworks.com/help/matlab/matlab_prog/local-functions-in-scripts.html" rel="nofollow noreferrer">local function</a> instead of a <a href="https://www.mathworks.com/help/matlab/matlab_prog/neste... | 271 |
solve differential equations | Solve system of differential equation in python | https://stackoverflow.com/questions/66354995/solve-system-of-differential-equation-in-python | <p>I'm trying to solve a system of differential equations in python.
I have a system composed by two equations where I have two variables, A and B.
The initial condition are that A0=1e17 and B0=0, they change simultaneously.
I wrote the following code using ODEINT:</p>
<pre><code>import numpy as np
from scipy.integrate... | <p>From <code>A*A'-B'=0</code> one concludes</p>
<pre class="lang-none prettyprint-override"><code>B = 0.5*(A^2 - A0^2)
</code></pre>
<p>Inserted into the first equation that gives</p>
<pre class="lang-none prettyprint-override"><code>A' = A - 0.5*A^2 + 0.5*A0^2
= 0.5*(A0^2+1 - (A-1)^2)
</code></pre>
<p>This means t... | 272 |
solve differential equations | Using parameters to solve differential equations in GEKKO python | https://stackoverflow.com/questions/70939582/using-parameters-to-solve-differential-equations-in-gekko-python | <p>I need to integrate over a system of differential equations in GEKKO and want to use parameters to alter a gradient.</p>
<p>Conceptually this works, but the output is not what I expected. I added a code snippet for a sample problem below to illustrate the problem.</p>
<p>The solver will integrate over a specified ti... | <p>Set <code>NODES=3</code> to get the desired output. The default in Gekko is <code>NODES=2</code> that is fast but not include interior calculation points for each step. Increasing the Nodes has the effect of increasing solution accuracy but also more variables to solve. For large problems with a long time horizon, i... | 273 |
solve differential equations | Solve ordinary differential equations using SciPy | https://stackoverflow.com/questions/40832798/solve-ordinary-differential-equations-using-scipy | <p>I have a following
<a href="https://i.sstatic.net/7RcuQ.png" rel="nofollow noreferrer">ordinary differential equation</a>
and numeric parameters <a href="https://i.sstatic.net/5Ol8B.png" rel="nofollow noreferrer">Sigma</a>=0.4, x(0) = 4 and dx(0)/dt = 0<br>
My task is to get Cauchy problem solution (Initial value p... | <p>Like Warren said, scipy.integrate.odeint is the 'SciPy' way to solve this.</p>
<p>But before you take your problem to SciPy (or whatever solver you end up using) you'll want to convert your 2nd order ODE to a first order ODE using something like: <a href="http://tutorial.math.lamar.edu/Classes/DE/SystemsDE.aspx" re... | 274 |
solve differential equations | Solving 1st order differential equations for matrices | https://stackoverflow.com/questions/59953428/solving-1st-order-differential-equations-for-matrices | <p>I'd like to code in python a coupled system of differential equations : <code>dF/dt=A(F)</code> where <code>F</code> is a matrix and <code>A(F)</code> is a function of the matrix <code>F</code>.</p>
<p>When <code>F</code> and <code>A(F)</code> are vectors the equation is solved using <code>scipy.integrate.odeint</c... | <p>As commented by Warren Weckesser in the comments, <code>odeintw</code> does the job.</p>
<pre><code>from odeintw import odeintw
import numpy as np
Y0_test=np.array([[0,1],[0,1]])
tmin, tmax, tstep = (0., 200., 1)
t_test=np.arange(tmin, tmax, tstep) #time vector
dydt_testm=np.array([[0.,1.],[2.,3.]])
def dydt_tes... | 275 |
solve differential equations | How to solve this system of differential equations where one differential is part of another? | https://stackoverflow.com/questions/57576549/how-to-solve-this-system-of-differential-equations-where-one-differential-is-par | <p>I need to solve this system of differential equations. </p>
<p>I tested it with removing <code>rk(3)</code> from the <code>rk(2)</code> equation and in that case I do get some solution. The code runs without error. However when I keep the <code>rk(3)</code> in the <code>rk(2)</code> equation I get a bunch of errors... | 276 | |
solve differential equations | Returning odd result when solving differential equations with solve_ivp | https://stackoverflow.com/questions/66756967/returning-odd-result-when-solving-differential-equations-with-solve-ivp | <p>I am trying to solve a series of differential equations as shown in the code below. But when I do simulate these differential equations, I am getting an inaccurate result. Here, I have 4 variables and I first reshaped my vector and then concatenated the values in hopes of having equal vector lengths for each of my v... | <p>There are several problems in the ODE function <code>testing</code></p>
<ul>
<li><p>The indentation of the return statement is wrong, it is in the loop, so triggered in the first run through it, for <code>i=0</code>.</p>
</li>
<li><p><code>F = 1/N * sum([V[i]])</code> is visibly wrong, you want to put F = 1/N * sum(... | 277 |
solve differential equations | Plot of ND solve differential equation with another parameter | https://stackoverflow.com/questions/24537894/plot-of-nd-solve-differential-equation-with-another-parameter | <p>I am trying to solve a differential equation numerically but I need to vary y0 for my plot and view result for constant x. I can solve my equation normally as I expected:but I can't get result when I try for my real purpose as you can see</p>
<pre><code>`\[Sigma] = 1;
n = 23.04;
Rop = y[x];
R = 0.5;
sz = R/(Rop + R... | <p>A variety of typos or misunderstandings</p>
<pre><code>\[Sigma] = 1;
n = 23.04;
Rop = y[x];
R = 0.5;
sz = R/(Rop + R);
F = -n*\[Sigma]*y[x]*(1 - 2*sz);
y0 = 0.8;
For[i = 1, i < 140, i++,
s = NDSolve[{y'[x] == F, y[0] == y0}, y, {x, 0, 0.07}];
Plot[Evaluate[y[x] /. s], {x, 0, 0.07}] // Print;
y0 = y0 + i*... | 278 |
solve differential equations | Solving coupled differential equations of quadratic drag | https://stackoverflow.com/questions/64410747/solving-coupled-differential-equations-of-quadratic-drag | <p><strong>Goal</strong></p>
<p>I have been attempting to solve and plot the following coupled differential equation belonging to quadratic drag:</p>
<p><a href="https://i.sstatic.net/onuqg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/onuqg.png" alt="enter image description here" /></a></p>
<p>The var... | <p>You can use a number of MATLAB built-in ODE solvers. <code>ode45</code> is usually a good place to start.</p>
<p>You have two positions and two velocities (4 states total), so you need to pass 4 ODEs to the solver <code>ode45</code> (one derivative for each state).
If <code>x(1)</code> is the x-position, <code>x(2)<... | 279 |
solve differential equations | Solving fractional differential equations in Matlab using fde12 function | https://stackoverflow.com/questions/16978825/solving-fractional-differential-equations-in-matlab-using-fde12-function | <pre><code>function dfdt=myfun(t,x)
dfdt = [...
x(2);
(1.5*((x(2))^2)*(cos(3*(x(1)))))-(((pi/2)^2) * ...
(sin((pi*t)/2)))-(20*((x(1))-(sin((pi*t)/2)))) - ...
((0.5*((x(2))^2)*abs(cos(3*(x(1)))))+0.1) * ...
sat(((x(2)-((pi/2)*cos((pi*t)/2))) + ...
(20*... | <p>RTFM - or in this case: <a href="http://www.mathworks.com/matlabcentral/fileexchange/32918-predictor-corrector-pece-method-for-fractional-differential-equations" rel="nofollow">the description</a>: </p>
<blockquote>
<p>The set of initial conditions Y0 is a matrix with a number of rows equal to the size of the pr... | 280 |
solve differential equations | How to solve differential equation in matlab | https://stackoverflow.com/questions/42324200/how-to-solve-differential-equation-in-matlab | <p>How can I show that <code>y(t)=Yo/Yo+(1-Yo)e^-at</code> is the solution of the differential equation <code>dy/dt=ay(1-y)</code> using MATLAB. What function should I use?</p>
| <p>if you want to simulate the results use the ode's family</p>
<p><a href="https://www.mathworks.com/help/matlab/ref/ode45.html" rel="nofollow noreferrer">https://www.mathworks.com/help/matlab/ref/ode45.html</a></p>
<p>else you can define your equation in syms and use diff</p>
<p><a href="https://www.mathworks.com/... | 281 |
solve differential equations | how to solve this system of differential equations numerically? | https://stackoverflow.com/questions/62245231/how-to-solve-this-system-of-differential-equations-numerically | <p><a href="https://i.sstatic.net/XO1BZ.png" rel="nofollow noreferrer">system of differential equations</a></p>
<p>Pls look at an image above</p>
<p>How can i build up the derivation function for this system to use scipy.integrate.odeint?
I tried to express 3 DEs as linear combinations of second derivatives of coordi... | <p>You have a system</p>
<pre><code>M(z)*D*z'' = F(t,z,z')
</code></pre>
<p>You can implement it using the linear systems solvers of numpy</p>
<pre class="lang-py prettyprint-override"><code>def system(t,u):
z,Dz = np.reshape(u,[-1,2])
D2z = diag([1,1/q,1/b]).dot( np.linalg.solve(M(z), F(t,z,Dz)) )
retur... | 282 |
solve differential equations | Solving a system of coupled differential equations with dsolve_system in python (sympy) | https://stackoverflow.com/questions/65393787/solving-a-system-of-coupled-differential-equations-with-dsolve-system-in-python | <p>I want to solve a system of 4 coupled differential equations with python (sympy):</p>
<pre><code>eqs = [Eq(cP1(t).diff(t), k1*cE1(t)**3), Eq(cE1(t).diff(t), -k1 * cE1(t)**3 + k6 * cE3(t)**2), Eq(cE2(t).diff(t), -k8 * cE2(t)), Eq(cE3(t).diff(t), k8 * cE2(t) - k6 * cE3(t)**2)]
</code></pre>
<p>When I try to solve the ... | <p>It's generally nice and friendly to show the complete code:</p>
<pre class="lang-py prettyprint-override"><code>In [18]: cP1, cE1, cE2, cE3 = symbols('cP1, cE1:4', cls=Function)
In [19]: t, k1, k6, k8 = symbols('t, k1, k6, k8')
In [20]: eqs = [Eq(cP1(t).diff(t), k1*cE1(t)**3), Eq(cE1(t).diff(t), -k1 * cE1(t)**3 + ... | 283 |
solve differential equations | How to solve a differential equation in formal power series? | https://stackoverflow.com/questions/46427586/how-to-solve-a-differential-equation-in-formal-power-series | <p>I would like to have first several coefficients of formal power series defined implicitly by a differential equation.</p>
<blockquote>
<p><strong>Example.</strong></p>
</blockquote>
<pre class="lang-py prettyprint-override"><code>import sympy as sp
sp.init_printing() # math as latex
from IPython.display import displ... | <p>UPDATE: an answer to a similar question has been posted <a href="https://stackoverflow.com/questions/46422538/how-to-solve-an-algebraic-equation-in-formal-power-series">here</a>. I use this second answer instead of the one presented below. The solution using standard functions from sympy works very slowly.</p>
<hr /... | 284 |
solve differential equations | Solving 3 coupled nonlinear differential equations using 4th order Runge Kutta in python | https://stackoverflow.com/questions/66664733/solving-3-coupled-nonlinear-differential-equations-using-4th-order-runge-kutta-i | <p>I am trying to plot orbits of a charged particle around a Reissner–Nordström blackhole(Charged blackhole).</p>
<p>I have three 2nd order differential equations as well as 3 first order differential equations. Due to the nature of the problem each derivative is in terms of proper time rather than time t. The equation... | <p>Take the three second order differential equations you have provided. These are the geodesic equations parametrized by proper time. You original metric however is rotationally invariant (i.e. SO(3) invariant), so it has a set of simple conservation laws, plus the conservation of the metric (i.e. conservation of prop... | 285 |
solve differential equations | Solving nonlinear differential equations in python | https://stackoverflow.com/questions/75479380/solving-nonlinear-differential-equations-in-python | <p>I am trying to solve the differential equation 4(y')^3-y'=1/x^2 in python. I am familiar with the use of odeint to solve coupled ODEs and linear ODEs, but can't find much guidance on nonlinear ODEs such as the one I'm grappling with.</p>
<p>Attempted to use odeint and scipy but can't seem to implement properly</p>
<... | <p>The problem is that you get 3 valid solutions for the direction at each point of the phase space (including double roots). But each selection criterion breaks down at double roots.</p>
<p>One way is to use a DAE solver (which does not exist in scipy) on the system <code>y'=v, 4v^3-v=x^-2</code></p>
<p>The second way... | 286 |
solve differential equations | Using Mathematica to solve this differential equation | https://stackoverflow.com/questions/54920753/using-mathematica-to-solve-this-differential-equation | <p>I want to describe the kinetics of a chemical reaction and my idea of a reaction model results (simplified) in a differential equation of the following form:</p>
<pre><code>y1'(t)=y1(t)+y2(t)
</code></pre>
<p>where y1 is the from an experiment measured concentration of a reactant and y2 the measured concentration ... | <p>You only have one equation to solve a simultaneous equation.</p>
<p>For example, this works:-</p>
<pre><code>vars = {x[t], y[t]};
eqns = {x'[t] == y[t], y'[t] == x[t]};
inits = {x[0] == 1, y[0] == 0};
DSolve[eqns, vars, t] // Simplify
sol = vars /. DSolve[Join[eqns, inits], vars, t][[1]]
Plot[sol, {t, 0, 2}]
</cod... | 287 |
solve differential equations | Solve system of complex differential equations in Octave | https://stackoverflow.com/questions/13480667/solve-system-of-complex-differential-equations-in-octave | <p>Well, I wanna solve a system of complex ODE in the form:</p>
<p>$ i\hbar \dfrac{\partial \rho}{\partial t} = \left[ H, \rho \right] $</p>
<p><a href="http://mathbin.heroku.com/rq65idQ" rel="nofollow" title="Paste Bin of Equation">http://mathbin.heroku.com/rq65idQ</a></p>
<p>where $\rho$ and $H$ are $n x n$ matric... | <p>I think the issue is because i is on the LHS of the equal sign rather than the RHS.</p>
<p>Have you tried?</p>
<pre><code>xdot(1) = <whatever your RHS expression is> / i;
xdot(2) = <whatever your RHS expression is> / i;
</code></pre>
| 288 |
solve differential equations | how to use solve_ivp solve Partial Differential Equations with spectral method? | https://stackoverflow.com/questions/60974226/how-to-use-solve-ivp-solve-partial-differential-equations-with-spectral-method | <p>I want to use the spectral method to solve partial differential equations. The equations like that, <a href="https://i.sstatic.net/vDAgk.png" rel="nofollow noreferrer">formula</a>,the initial condition is u(t=0,x)=(a^2)*sech(x),u'_t (t=0)=0.</p>
<p>To solve it, I use the python with the spectral method. Following i... | <p>You have some slight problem with the design of your state vector and using this in the ODE function. The overall intent is that <code>u[:N]</code> is the wave function and <code>u[N:]</code> its time derivative. Now you want the second space derivative of the wave function, thus you need to use</p>
<pre><code>uxx=... | 289 |
solve differential equations | How to solve and plot differential equations in R | https://stackoverflow.com/questions/25001337/how-to-solve-and-plot-differential-equations-in-r | <p>Taken from Sal Khan's lecture <a href="https://www.youtube.com/watch?v=oiDvNs15tkE" rel="nofollow">https://www.youtube.com/watch?v=oiDvNs15tkE</a> of the Khan academy, if I know that dN/dt=rN(1-(N/K)) (the logistic differential equation)</p>
<p>How can I solve for N and plot the N=f(t) with R?</p>
<p>Thanks</p>
| <p>This logistic equation has an analytical solution (see for example <a href="https://www.youtube.com/watch?v=j_Taf2Tgggo" rel="noreferrer">here</a>), so you can plot it directly. Another option is to solve it numerically using one of the available solvers (see <a href="http://cran.r-project.org/web/views/Differential... | 290 |
solve differential equations | Can we prioritise SymPy over SciPy while solving well posed differential equations? | https://stackoverflow.com/questions/67430010/can-we-prioritise-sympy-over-scipy-while-solving-well-posed-differential-equatio | <p>Till now, I haven't faced any issue while solving well-posed differential equations problems using sympy only in python such as</p>
<ol>
<li>Solving a second order linear differential equation:</li>
</ol>
<pre><code>import matplotlib.pyplot as plt
from sympy import dsolve, symbols, Function, Eq
t= symbols('t')
x= s... | 291 | |
solve differential equations | Solve system of differential equation with embedded non diferential equations, using Octave/Matlab (see picture) | https://stackoverflow.com/questions/60235976/solve-system-of-differential-equation-with-embedded-non-diferential-equations-u | <p>I have <a href="https://i.sstatic.net/1txPv.png" rel="nofollow noreferrer">the following equation system (click to see picture)</a>
, and would like to solve for X(t), Y(t), Z(t), hopefully using Octave/Matlab, which I'm familiar with, but I would not mind solving it by any other means necessary. </p>
<p>Now, Fsolv... | <p>If you know <code>y</code>, you can solve for <code>x</code>, and this even unconditionally as the second equation in monotonous in <code>x</code></p>
<pre><code>x = fsolve(@(x) y^2-1413.7*x-1095.2*cos(x)+2169, 0)
</code></pre>
<p>Then once you know <code>x</code>, you can solve for <code>z</code> using the known ... | 292 |
solve differential equations | Solving non-linear coupled differential equations in python | https://stackoverflow.com/questions/51313086/solving-non-linear-coupled-differential-equations-in-python | <p>I am working on simulation of a system that contains coupled differential equations. My main aim is to solve the mass balance in steady condition and feed the solution of steady state as initial guess for the dynamic simulation.
There are basically three state variables Ss,Xs and Xbh. The rate equations look like th... | <p>This is a solution to getting negative values for your solution: instead of using fsolve, use least_squares, which allows you to set bounds to the possible values.</p>
<p>In the top, import:</p>
<pre><code>from scipy.optimize import least_squares
</code></pre>
<p>And replace the fsolve statement with:</p>
<pre><... | 293 |
solve differential equations | How to numerically solve this system of arbitrary number of differential equations? | https://stackoverflow.com/questions/63354720/how-to-numerically-solve-this-system-of-arbitrary-number-of-differential-equatio | <p>How can I solve a system of k differential equations with derivatives appearing in every equation? I am trying to use Scipy's solve_ivp.</p>
<p>All the equations are of the following form:</p>
<p><a href="https://i.sstatic.net/3Gqqn.png" rel="nofollow noreferrer">equations</a></p>
<p>How can this system of equations... | <p>If you set <code>C[i]=B[i,i]</code> then you can transform the equations to the linear system <code>B*z'=A</code>. This can be solved as</p>
<pre><code>zdot = numpy.linalg.solve(B,A)
</code></pre>
<p>so that the derivative is this constant solution of a constant linear system, and the resulting solution for <code>z<... | 294 |
solve differential equations | Mathematica solving differential equations | https://stackoverflow.com/questions/4020606/mathematica-solving-differential-equations | <p>I would like to numerically find the solution to </p>
<p><code>u_t - u_xx - u_yy = f</code> on the square y ∈ [0,1], x ∈ [0,1]</p>
<p>where f=1 if in the unit circle and f=0 otherwise. The boundary conditions are u=0 on all four edges.</p>
<p>I have been trying to use ND-solve for ages but I keep getting error ... | <p>The Mathematica help files are incredibly complete for stuff like this. I'm going to <a href="http://reference.wolfram.com/mathematica/ref/NDSolve.html" rel="nofollow">reference the online version</a>, but note that, in the help browser in Mathematica, you can <strong>interactively modify and evaluate the help exam... | 295 |
solve differential equations | How to solve a differential equation with time dependent parameters? | https://stackoverflow.com/questions/66604009/how-to-solve-a-differential-equation-with-time-dependent-parameters | <p>I have a differential equation with time varying function W_at(t). How can I solve it using sympy's <code>dsolve</code> with initial conditions.</p>
<pre><code>from sympy import *
init_printing(use_unicode=True)
theta_vr, theta_vd, theta_vo, t = symbols('theta_vr theta_vd theta_vo t')
W_at = Function('W_at')
S_vt =... | 296 | |
solve differential equations | Using scilab to solve and plot differential equations | https://stackoverflow.com/questions/29477235/using-scilab-to-solve-and-plot-differential-equations | <p>How can I solve the second order differential equation using scilab ode() function.
(For example: y'' + 3y' +2y = f(x), y(0)=0, y'(0)=0)
And then plot the result of function y(x).</p>
<p>I want to use this to model the RLC-circuit signal with step-function input</p>
<p>Here is the code I tried</p>
<pre><code>func... | <p>You were nearly there, you only had problems with the shape of the vectors and how that affects the collection of the trajectory, that is, the construction of the return array of <code>ode</code>, as an array of vectors.</p>
<pre><code>function y=u(t)
y=(sign(t)+1)/2
endfunction
L=0.001
R=10
C=0.000001
functi... | 297 |
solve differential equations | Matrix differential equation. Solve Ax'=Bx+b | https://stackoverflow.com/questions/50396666/matrix-differential-equation-solve-ax-bxb | <p>I have the matrix differential equation <code>Ax'=Bx+b</code>, where <code>A</code> and <code>B</code> are matrices of <code>N*N</code>, and <code>b</code> is a vector.</p>
<p>I want to solve it with python. Hope someone could help me.</p>
<p>Cheers!</p>
| <p>If your matrix <code>A</code> is regular, the function to pass to <code>odeint</code> is </p>
<pre><code>def odefunc(x,t):
return numpy.linalg.solve(A, B.dot(x)+c)
</code></pre>
<p>You can of course also compute the inverse of <code>A</code> and left-multiply the equation with it.</p>
<pre><code>B = numpy.lin... | 298 |
solve differential equations | how to specify final value (rather than initial value) for solving differential equations | https://stackoverflow.com/questions/40580485/how-to-specify-final-value-rather-than-initial-value-for-solving-differential | <p>I would like to solve a differential equation in R (with <code>deSolve</code>?) for which I do not have the initial condition, but only the final condition of the state variable. How can this be done?</p>
<p>The typical code is: <code>ode(times, y, parameters, function ...)</code> where <code>y</code> is the initial... | <p>Are your equations <a href="https://en.wikipedia.org/wiki/Time_reversibility" rel="nofollow noreferrer">time reversible</a>, that is, can you change your differential equations so they run backward in time? Most typically this will just mean reversing the sign of the gradient. For example, for a simple exponential ... | 299 |
gradient descent implementation | Fast gradient-descent implementation in a C++ library? | https://stackoverflow.com/questions/11524657/fast-gradient-descent-implementation-in-a-c-library | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/11513926/fast-gradient-descent-implementation-in-a-c-library">Fast gradient-descent implementation in a C++ library?</a> </p>
</blockquote>
<p>I'm looking to run a gradient descent optimization to minimize the ... | 300 | |
gradient descent implementation | Is my implementation of stochastic gradient descent correct? | https://stackoverflow.com/questions/21352101/is-my-implementation-of-stochastic-gradient-descent-correct | <p>I am trying to develop stochastic gradient descent, but I don't know if it is 100% correct.</p>
<ul>
<li>The cost generated by my stochastic gradient descent algorithm is sometimes very far from the one generated by FMINUC or Batch gradient descent.</li>
<li>while batch gradient descent cost converge when I set a l... | <p>This is pretty much ok. If you are worried about choosing the appropriate learning rate <code>alpha</code>, you should think about applying a <strong>line search</strong> method.</p>
<p>Line search is a method which chooses an optimal learning rate for gradient descent at every iteration, which is better than using... | 301 |
gradient descent implementation | Stochastic gradient descent from gradient descent implementation in R | https://stackoverflow.com/questions/37485138/stochastic-gradient-descent-from-gradient-descent-implementation-in-r | <p>I have a working implementation of multivariable linear regression using gradient descent in R. I'd like to see if I can use what I have to run a stochastic gradient descent. I'm not sure if this is really inefficient or not. For example, for each value of α I want to perform 500 SGD iterations and be able to specif... | <p>Sticking with what you have now</p>
<pre><code>## all of this is the same
download.file("https://raw.githubusercontent.com/dbouquin/IS_605/master/sgd_ex_data/ex3x.dat", "ex3x.dat", method="curl")
x <- read.table('ex3x.dat')
x <- scale(x)
download.file("https://raw.githubusercontent.com/dbouquin/IS_605/master... | 302 |
gradient descent implementation | Gradient Descent implementation in Python | https://stackoverflow.com/questions/32792703/gradient-descent-implementation-in-python | <p>I got stucked at a point where I am implementing gradient descent in python.</p>
<p>The formula for gradient descent is:</p>
<pre><code>for iter in range(1, num_iters):
hypo_function = np.sum(np.dot(np.dot(theta.T, X)-y, X[:,iter]))
theta_0 = theta[0] - alpha * (1.0 / m) * hypo_function
theta_1 = thet... | <p><strong>np.dot(a,b)</strong> takes the inner product of a and b if a and b are vectors (1-D arrays) If a and b are 2D arrays, <strong>np.dot(a,b)</strong> does matrix multiplication.</p>
<p>It will throw ValueError if there is a mismatch between the size of the last dimension of a and the second to last dimension o... | 303 |
gradient descent implementation | Gradient descent implementation | https://stackoverflow.com/questions/9163801/gradient-descent-implementation | <p>I've implemented both the batch and stochastic gradient descent. I'm experiencing some issues though. This is the stochastic rule:</p>
<pre><code>1 to m {
theta(j):=theta(j)-step*derivative (for all j)
}
</code></pre>
<p>The issue I have is that, even though the cost function is becoming smaller and smaller ... | <p>Gradient descent is a local search method for minimizing a function. When it reaches a local minimum in the parameter space, it won't be able to go any further. This makes gradient descent (and other local methods) prone to getting stuck in local minima, rather than reaching the global minimum. The local minima may ... | 304 |
gradient descent implementation | Stochastic gradient Descent implementation - MATLAB | https://stackoverflow.com/questions/5117337/stochastic-gradient-descent-implementation-matlab | <p>I'm trying to implement "<a href="http://en.wikipedia.org/wiki/Stochastic_gradient_descent" rel="noreferrer">Stochastic gradient descent</a>" in MATLAB. I followed the algorithm exactly but I'm getting a VERY VERY large w (coffients) for the prediction/fitting function. Do I have a mistake in the algorithm ?</p>
<p... | <p>If you use too big learning rate, SGD is likely to diverge.<br>
The learing rate should converge to zero.</p>
| 305 |
gradient descent implementation | Gradient descent implementation - absolute error issue | https://stackoverflow.com/questions/47370541/gradient-descent-implementation-absolute-error-issue | <p>I am trying to implement gradient descent algorithm in Python. When I plot the history of the cost function it seems to be converging but the mean absolute error I get with my implementation is way worse than the one I get from sklearn's <em>linear_model</em>. I couldn't figure out what is wrong with my implementati... | <p>It seems you have missed a bias / intercept column and coefficient.</p>
<p>Hypothesis for linear function should look like:</p>
<pre><code>H = theta_0 + theta_1 * x
</code></pre>
<p>in your implementation it looks like as follows:</p>
<pre><code>H = theta_1 * x
</code></pre>
| 306 |
gradient descent implementation | Is there is a gradient descent implementation that uses matrix matrix multiplication? | https://stackoverflow.com/questions/43411013/is-there-is-a-gradient-descent-implementation-that-uses-matrix-matrix-multiplica | <p>I'm using the below gradient descent implementation in <a href="https://github.com/schneems/Octave/blob/master/mlclass-ex1/gradientDescent.m" rel="nofollow noreferrer">Octave for ML</a>.</p>
<p>I tried first to increase number of CPU cores and run Octave multithreaded using OpenBlas but still I didn't get the resul... | 307 | |
gradient descent implementation | Gradient Descent implementation in python? | https://stackoverflow.com/questions/55210443/gradient-descent-implementation-in-python | <p>I have tried to implement gradient descent and it was working properly when I tested it on sample dataset but it's not working properly for boston dataset.</p>
<p>Can you verify what's wrong with the code. why I'm not getting a correct theta vector?</p>
<pre><code>import numpy as np
from sklearn.datasets import lo... | <p>Consider this (unrolled some statements for better visibility):</p>
<pre><code>for i in range(n_iterations):
y_hat = X_train1.dot(theta)
error = y_hat - y_train[:, None]
gradients = 2/m * X_train1.T.dot(error)
if np.linalg.norm(X_train1) < tol:
break
theta = theta - (eta * gradients)... | 308 |
gradient descent implementation | Fast gradient-descent implementation in a C++ library? | https://stackoverflow.com/questions/11513926/fast-gradient-descent-implementation-in-a-c-library | <p>I'm looking to run a gradient descent optimization to minimize the cost of an instantiation of variables. My program is very computationally expensive, so I'm looking for a popular library with a fast implementation of GD. What is the recommended library/reference?</p>
| <p><a href="http://www.gnu.org/software/gsl/" rel="noreferrer">GSL</a> is a great (and free) library that already implements common functions of mathematical and scientific interest.</p>
<p>You can peruse through the entire <a href="http://www.gnu.org/software/gsl/manual/html_node/" rel="noreferrer">reference manual o... | 309 |
gradient descent implementation | Gradient Descent Implementation in Python returns Nan | https://stackoverflow.com/questions/15211715/gradient-descent-implementation-in-python-returns-nan | <p>I am trying to implement gradient descent in python; the implementation works when I try it with training_set1 but it returns not a number(nan) when I try it training_set. Any idea why my code is broken?</p>
<pre><code>from collections import namedtuple
TrainingInstance = namedtuple("TrainingInstance", ['X', 'Y'])... | <p>Reduce <code>training_rate</code> so that the objective decreases at each iteration.</p>
<p>See Figure 6. in this paper: <a href="http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf" rel="nofollow">http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf</a></p>
| 310 |
gradient descent implementation | Pure Python Implementation of gradient descent | https://stackoverflow.com/questions/63094866/pure-python-implementation-of-gradient-descent | <p>I have tried to implement gradient descent myself using Python. I know there are similar topics on this, but for my attempt, my guess slope can always get really close to the real slope, but the guess intercept never matched or even come close to the real intercept. Does anyone know why is that happening?</p>
<p>Als... | <p>The reason for overflow is the missing factor <code>(2/n)</code>. I have broadly shown the use of negative signs for more clarification.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
intercept = -5
slope = -4
# y = mx + b
x = []
y = []
for i in range(0, 100):
x.append(i/300)
y.append((... | 311 |
gradient descent implementation | Gradient descent implementation is not working in Julia | https://stackoverflow.com/questions/47189943/gradient-descent-implementation-is-not-working-in-julia | <p>I am trying to Implement <strong>gradient Descent</strong> algorithm from scratch to find the slope and intercept value for my linear fit line.</p>
<p>Using the package and calculating slope and intercept, I get slope = 0.04 and intercept = 7.2 but when I use my gradient descent algorithm for the same problem, I ge... | <p>I have not done the math, but instead wrote the tests. It seems you got a sign error when assigning m and c.</p>
<p>Also, writing the tests really helps, and Julia makes it simple :)</p>
<pre><code>function GradientDescent(x, y)
m=0.0
c=0.0
for i=1:10000
for k=1:length(x)
... | 312 |
gradient descent implementation | mini-batch gradient descent implementation in tensorflow | https://stackoverflow.com/questions/40367514/mini-batch-gradient-descent-implementation-in-tensorflow | <p>When reading an tensorflow implementation for a deep learning model, I am trying to understand the following code segment included in the training process. </p>
<pre><code>self.net.gradients_node = tf.gradients(loss, self.variables)
for epoch in range(epochs):
total_loss = 0
for step in rang... | <p>This is not related to mini batch SGD.</p>
<p>It computes average gradient over all timesteps. After the first timestep <code>avg_gradients</code> will contain the gradient that was just computed, after the second step it will be elementwise mean of the two gradients from the two steps, after <code>n</code> steps i... | 313 |
gradient descent implementation | Implementing a gradient descent | https://stackoverflow.com/questions/58833048/implementing-a-gradient-descent | <p>I'm trying to implement a gradient descent in Go. My goal is to predict the cost of a car from it's mileage.
Here is my data set:</p>
<pre><code>km,price
240000,3650
139800,3800
150500,4400
185530,4450
176000,5250
114800,5350
166800,5800
89000,5990
144500,5999
84000,6200
82029,6390
63060,6390
74000,6600
97500,6800
... | <p><a href="https://en.wikipedia.org/wiki/Ordinary_least_squares#Simple_linear_regression_model" rel="nofollow noreferrer">Linear Regression</a> is really simple: </p>
<pre><code>// yi = alpha + beta*xi + ei
func linearRegression(x, y []float64) (float64, float64) {
EX := expected(x)
EY := expected(y)
EXY... | 314 |
gradient descent implementation | Gradient Descent implementation in octave | https://stackoverflow.com/questions/10591343/gradient-descent-implementation-in-octave | <p>I've actually been struggling against this for like 2 months now. What is it that makes these different? </p>
<pre><code>hypotheses= X * theta
temp=(hypotheses-y)'
temp=X(:,1) * temp
temp=temp * (1 / m)
temp=temp * alpha
theta(1)=theta(1)-temp
hypotheses= X * theta
temp=(hypotheses-y)'
temp=temp * (1 / m)
temp=te... | <p>What you're doing in the first example in the second block you've missed out a step haven't you? I am assuming you concatenated X with a vector of ones.</p>
<pre><code> temp=X(:,2) * temp
</code></pre>
<p>The last example will work but can be vectorized even more to be more simple and efficient.</p>
<p>I've ass... | 315 |
gradient descent implementation | Tried implementing Gradient Descent | https://stackoverflow.com/questions/61714403/tried-implementing-gradient-descent | <p>I am totally new to ML and python, Read linear regression and tried to implement gradient descent </p>
<p>first, Could anyone please let me know what wrong I am doing?</p>
<p>Input Data - </p>
<pre><code> x = np.array([1,2,3,4,5,6])
y = (2*x + 5) + np.random.normal(0, 1, len(x))
curve = pd.DataFrame(n... | <p>You have two problems here.
First of all you defined the learning rate but didn't use it</p>
<pre><code> m = m - learningRate * sum(Dm)/n
c = c - learningRate* sum(Dc)/n
</code></pre>
<p>Secondly your learning rate is to large. Choose a value like 0.01</p>
<p>If you change your print statement to
prin... | 316 |
gradient descent implementation | Cost function not decreasing in gradient descent implementation | https://stackoverflow.com/questions/23576301/cost-function-not-decreasing-in-gradient-descent-implementation | <p>I am trying implemented batch gradient descent in C language. The problem is, my cost function increases dramatically in every turn and I am not able to understand what is wrong. I checked my code several times and it seems to me that I coded exactly the formulas. Do you have any suggestions or ideas what might be t... | 317 | |
gradient descent implementation | Implementation of Gradient Descent (Matlab) | https://stackoverflow.com/questions/56115458/implementation-of-gradient-descent-matlab | <p>I have a problem with simple implemenation of Gradient Descent algorithm -
I wrote the following code, just turning the math of GD into a matlab code, but it does not converge. Due to the simplicity of this implementation, I think the I'm missing here very crucial thing about wroking with Matlab.</p>
<p>The goal o... | 318 | |
gradient descent implementation | Stochastic gradient descent implementation with Python's numpy | https://stackoverflow.com/questions/39975050/stochastic-gradient-descent-implementation-with-pythons-numpy | <p>I have to implement stochastic gradient descent using python numpy library. For that purpose I'm given the following function definitions:</p>
<pre><code>def compute_stoch_gradient(y, tx, w):
"""Compute a stochastic gradient for batch data."""
def stochastic_gradient_descent(
y, tx, initial_w, batch_si... | <p>In a typical implementation, a mini-batch gradient descent with batch size B should pick B data points from the dataset randomly and update the weights based on the computed gradients on this subset. This process itself will continue many number of times until convergence or some threshold maximum iteration. Mini-ba... | 319 |
gradient descent implementation | Having trouble making update in gradient descent implementation? | https://stackoverflow.com/questions/66874237/having-trouble-making-update-in-gradient-descent-implementation | <p>Hi I am working on implementing gradient descent with backtracking line search. However when I try to update f(x0) the value doesn't change. Could it be something going on with the lambda expression, I am not too familiar with them?</p>
<pre><code>import numpy as np
import math
alpha = 0.1
beta = 0.6
f = lambda x: ... | <p><strong>Update for new code</strong></p>
<p>OK, your numbers now change too much!</p>
<p>When writing these routines stepping through the code with a debugger is really useful to check that the code is doing what you want. In this case you'll see that on the second pass through the loop <code>x0 = [-1.32e+170, 3.96e... | 320 |
gradient descent implementation | Implementing gradient descent with Scala and Breeze - error : could not find implicit value for parameter op: | https://stackoverflow.com/questions/37624288/implementing-gradient-descent-with-scala-and-breeze-error-could-not-find-imp | <p>I'm attempting to apply a gradient descent implementation in Scala and breeze based on Octave from : <a href="https://stackoverflow.com/questions/10591343/gradient-descent-implementation-in-octave">Gradient Descent implementation in octave</a> </p>
<p>The octave code I'm attempting to re-write is :</p>
<pre><code>... | <pre><code> val myvalue = (mymatrix - ((1 / m) * (( (xv * mymatrix - yv).t * xv).t * .0001)
</code></pre>
<p><code>xv</code> is Vector and the <code>mymatrix</code> is the <strong>Matrix</strong> which is <strong>unsupported</strong>.
that is the error u are encountering</p>
| 321 |
gradient descent implementation | Why I'm getting a huge cost in Stochastic Gradient Descent Implementation? | https://stackoverflow.com/questions/64791138/why-im-getting-a-huge-cost-in-stochastic-gradient-descent-implementation | <p>I've run into some problems while trying to implement Stochastic Gradient Descent, and basically what is happening is that my cost is growing like crazy and I don't have a clue why.</p>
<p>MSE implementation:</p>
<pre><code>def mse(x,y,w,b):
predictions = x @ w
summed = (np.square(y - predictions - b)).mean... | <p>Here are a few suggestions:</p>
<ul>
<li>your learning rate is too big for the training: changing it to something like 1e-3 should be fine.</li>
<li>your update part could be slightly modified as follows:</li>
</ul>
<pre><code>def stochastic_gradient_descent(X,y,w,b,learning_rate=0.01,iterations=500,batch_size =100)... | 322 |
gradient descent implementation | Issue with gradient descent implementation of linear regression | https://stackoverflow.com/questions/41150457/issue-with-gradient-descent-implementation-of-linear-regression | <p>I am taking <a href="https://www.coursera.org/learn/ml-regression" rel="nofollow noreferrer">this Coursera class</a> on machine learning / linear regression. Here is how they describe the gradient descent algorithm for solving for the estimated OLS coefficients:</p>
<p><a href="https://i.sstatic.net/QB9TY.png" rel... | <p>Try decreasing the value of eta. Gradient descent can diverge if eta is too high.</p>
| 323 |
gradient descent implementation | How to implement stochastic gradient descent | https://stackoverflow.com/questions/55880425/how-to-implement-stochastic-gradient-descent | <p>In stochastic gradient descent, we often consider the objective function as a sum of a finite number of functions: </p>
<pre><code> f(x)=∑fi(x) where i = 1 : n
</code></pre>
<p>At each iteration, rather than computing the gradient <code>∇f(x)</code>, stochastic gradient descent randomly samples <code>i... | <p>It seems there is a lot of confusion going on here for you. Here are the two main things I see wrong so far, in order of importance:</p>
<ol>
<li>Stochastic gradient descent is used when you have a lot of data, for which evaluating the objective function for all training observations at each iteration is computatio... | 324 |
gradient descent implementation | Gradient descent impementation python - contour lines | https://stackoverflow.com/questions/50723432/gradient-descent-impementation-python-contour-lines | <p>As a self study exercise I am trying to implement gradient descent on a linear regression problem from scratch and plot the resulting iterations on a contour plot. </p>
<p>My gradient descent implementation gives the correct result (tested with Sklearn) however the gradient descent plot doesn't seem to be <strong>p... | <p>The problem with the contour graph is that the scales of theta0 and theta1 are different. Just add "plt.axis('equal')" to the contour plot instructions and you will see that the gradient descent is in fact perpendicular to the contour lines.</p>
<p><a href="https://i.sstatic.net/Gwzeq.png" rel="nofollow noreferrer"... | 325 |
gradient descent implementation | What is wrong with my gradient descent implementation for Linear regression in Python | https://stackoverflow.com/questions/69071325/what-is-wrong-with-my-gradient-descent-implementation-for-linear-regression-in-p | <p>I've been trying to refresh my fundamental knowledge of stats, so I tried to implement simple linear regression in python using gradient descent.</p>
<p>The code correctly minimizes the MSE, however it does so by making a straight horizontal line across the dataset
<a href="https://i.sstatic.net/6lR4c.png" rel="nofo... | <p>I found the answer, the issue was the shape of the train_X was (10,1) so when I multiplied with the errors to find the derivative of the slope, it produced the wrong result.</p>
<p>I fixed it by flattening the train_X</p>
| 326 |
gradient descent implementation | How to implement multivariate linear stochastic gradient descent algorithm in tensorflow? | https://stackoverflow.com/questions/36031324/how-to-implement-multivariate-linear-stochastic-gradient-descent-algorithm-in-te | <p>I started with simple implementation of single variable linear gradient descent but don't know to extend it to multivariate stochastic gradient descent algorithm ?</p>
<p>Single variable linear regression </p>
<pre><code>import tensorflow as tf
import numpy as np
# create random data
x_data = np.random.rand(100).... | <p>You have two part in your question:</p>
<ul>
<li>How to change this problem to a higher dimension space.</li>
<li>How to change from the batch gradient descent to a stochastic gradient descent.</li>
</ul>
<p>To get a higher dimensional setting, you can define your linear problem <code>y = <x, w></code>. Then... | 327 |
gradient descent implementation | Implementing a linear regression using gradient descent | https://stackoverflow.com/questions/58996556/implementing-a-linear-regression-using-gradient-descent | <p>I'm trying to implement a linear regression with gradient descent as explained in this article (<a href="https://towardsdatascience.com/linear-regression-using-gradient-descent-97a6c8700931" rel="nofollow noreferrer">https://towardsdatascience.com/linear-regression-using-gradient-descent-97a6c8700931</a>).
I've foll... | <blockquote>
<p>Why would a formula work on one data set and not another one?</p>
</blockquote>
<p>In addition to sascha's remarks, here's another way to look at problems of this application of gradient descent: The algorithm offers no guarantee that an iteration yields a better result than the previous, so it doesn... | 328 |
gradient descent implementation | stochastic gradient descent algorithm implementation in matlab | https://stackoverflow.com/questions/43016224/stochastic-gradient-descent-algorithm-implementation-in-matlab | <p>I implemented stochastic gradient descent algorithm matlab but unable to get proper result. First, I shuffled the training set and update each weight using one sample at a time. Is there any mistake ?</p>
<pre><code>function [theta, J] = gradientdescent(x, y,theta,alpha,epochs)
m = length(y);
J = zeros(epochs, 1)... | 329 | |
gradient descent implementation | Issue implementing gradient descent | https://stackoverflow.com/questions/46555883/issue-implementing-gradient-descent | <p>I'm implementing gradient descent from scratch and I've got a segment of code which is giving me trouble.</p>
<pre><code>temp = theta_new[j]
theta_new[j] = theta_new[j] - alpha*deriv
theta_old[j] = temp
</code></pre>
<p>It's not changing <code>theta_new[j]</code>. If I print <code>theta_new[j]</code> just after th... | <p>You should use <code>deep copy</code> to copy objects and create a new memory value and a new pointer :</p>
<pre><code>import copy
theta_old = copy.deepcopy(theta_new)
theta_new[j] = theta_new[j] - alpha*deriv
...
</code></pre>
<p><a href="https://docs.python.org/3/library/copy.html" rel="nofollow noreferrer">http... | 330 |
gradient descent implementation | vector implementation of Gradient Descent with multiple theta | https://stackoverflow.com/questions/38341783/vector-implementation-of-gradient-descent-with-multiple-theta | <p>I am trying to implement gradient descent in octave for function having multiple theta value . Do you have any sample so?</p>
| <p>It was already answered in other question 4 years ago:
<a href="https://stackoverflow.com/questions/10591343/gradient-descent-implementation-in-octave">Gradient Descent implementation in octave</a></p>
<p>Use the code from there and probably update it a bit to match your specifics.</p>
| 331 |
gradient descent implementation | How to implement mini-batch gradient descent in python? | https://stackoverflow.com/questions/38157972/how-to-implement-mini-batch-gradient-descent-in-python | <p>I have just started to learn deep learning. I found myself stuck when it came to gradient descent. I know how to implement batch gradient descent. I know how it works as well how mini-batch and stochastic gradient descent works in theory. But really can't understand how to implement in code.</p>
<pre><code>import n... | <p>This function returns the mini-batches given the inputs and targets:</p>
<pre><code>def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
assert inputs.shape[0] == targets.shape[0]
if shuffle:
indices = np.arange(inputs.shape[0])
np.random.shuffle(indices)
for start_idx in ... | 332 |
gradient descent implementation | How to implement naive batch gradient descent? | https://stackoverflow.com/questions/45562063/how-to-implement-naive-batch-gradient-descent | <p>everyone. I have a question about the implement of gradient descent. I have found several optimizers, like ada_grad, adam, sgd and so on, they're perfect. But I'm attempting to implement the naive gradient method batch gradient descent that is with the fix learning rate and acts on the whole examples in each batch. ... | <p>How about using large enough batch-size and SGD? It is equivalent to simple Gradient Descent method.</p>
| 333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.