Skip to content

Instantly share code, notes, and snippets.

@adam-hanna
Last active August 21, 2023 06:59
Show Gist options
  • Save adam-hanna/474e3c6c31ac64dd77faaa896281a8e4 to your computer and use it in GitHub Desktop.
Save adam-hanna/474e3c6c31ac64dd77faaa896281a8e4 to your computer and use it in GitHub Desktop.
Goal seek example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Goal Seek Example</title>
<!--
note: update the contents between the <script>{update this stuff!}</script> tags, below, with the most up-to-date \
code from: https://raw.githubusercontent.com/adam-hanna/goal-seek/develop/dist/index.min.js
-->
<script type="text/javascript">
!function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.IsNanError=TypeError("resulted in NaN"),e.FailedToConvergeError=Error("failed to converge");e.default=({fn:r,fnParams:a,percentTolerance:o,maxIterations:t,maxStep:n,goal:l,independentVariableIdx:i})=>{let s,d,f,p,u;const N=o/100*l;for(let o=0;o<t;o++){if(d=r.apply(null,a)-l,isNaN(d))throw e.IsNanError;if(Math.abs(d)<=Math.abs(N))return a[i];if(p=a[i],u=p+d,Math.abs(u-p)>n&&(u=u>p?p+n:p-n),a[i]=u,f=r.apply(null,a)-l,isNaN(f))throw e.IsNanError;s=(f-d)/d,0===s&&(s=1e-4),u=p-d/s,n&&Math.abs(u-p)>n&&(u=u>p?p+n:p-n),a[i]=u}throw e.FailedToConvergeError}}("undefined"==typeof goalSeeker?goalSeeker={}:goalSeeker);
</script>
</head>
<body>
<div id="result">waiting...</div>
<script>
var element = document.getElementById("result");
function ready() {
var fn = (x,y,z) => x * y * z;
var fnParams = [4,5,6];
try {
var result = goalSeeker.default({
fn,
fnParams,
percentTolerance: 1,
maxIterations: 1000,
maxStep: 1,
goal: 140,
independentVariableIdx: 2
});
console.log(`result: ${result}`);
element.innerHTML = result;
} catch (e) {
console.error('error', e);
}
}
window.onload = ready;
</script>
</body>
</html>
@bink24
Copy link

bink24 commented Aug 21, 2023

Hi @adam-hanna
Thanks for share this code. I have a question regarding the variable fn.
Is it possible to add conditional range as following code?

var fn = (x, y, z) => {
    x = z - y + (
        z >= 0 && z <=  10000 ? 10 : (
            z >= 10001 && z <= 20000 ? 20 : 0
        )
    )
}

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment