public static void SaveToFile(ETopology top, EFunction fun, EConstrictionFactor cons, List <List <Double> > outputSamples, int id) { List <String> stringList = new List <string>(); String s = ""; for (int i = 0; i < Parameters.SAMPLE_COUNT; i++) { s += (i + 1) + "\t"; } stringList.Add(s + "Fitness\tIterations (Average from 30 samples)"); for (int i = 0; i < Parameters.ITERATION_AMOUNT; i++) { String temp = ""; Double sum = 0d; for (int j = 0; j < Parameters.PARTICLE_AMOUNT; j++) { sum += outputSamples[j][i]; temp += outputSamples[j][i] + "\t"; } stringList.Add(temp + i + "\t" + sum / Parameters.PARTICLE_AMOUNT); } System.IO.File.WriteAllLines(@"WriteLines" + top.ToString() + "," + fun.ToString() + "," + cons.ToString() + "," + id + ".txt", stringList.ToArray()); }
static private bool WriteFunction(EFunctionFile eFile, EFunction eFunction) { try { StringBuilder result = new StringBuilder(); StringBuilder argsStringBuilder = new StringBuilder(); List <EArg> segmentsList, mandatoryList, optionalList, formArgList, allArgsList; EArg bodyArg; Logger.LogInfoIfDebugLevel(DebugLevels.Functions | DebugLevels.All, "\tFunction " + eFunction.functionName); string functionName = Char.ToLowerInvariant(eFunction.functionName[0]) + eFunction.functionName.Substring(1); eFunction.frontendReturnTypeName = FlutterWatcher.GetFlutterType(eFunction.returnTypeName, out bool isAnotherEntityImport); //antes era GetFlutterFuctionReturnType string operation = Helper.GetRESTOperation(eFile, eFunction); if (string.IsNullOrEmpty(operation)) { return(false); } if (!GetFunctionArgs(eFunction, ref argsStringBuilder, out allArgsList, out segmentsList, out mandatoryList, out optionalList, out formArgList, out bodyArg)) { Logger.LogError("unable to get funcion parameters to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(false); } result.Append("\tstatic Future<" + eFunction.frontendReturnTypeName + "> " + functionName + "(" + argsStringBuilder.ToString() + ") async {"); string functionBody = GetFunctionBody(eFile, eFunction, operation, segmentsList, mandatoryList, optionalList, formArgList, bodyArg); result.Append(functionBody); eFunction.frontendFunctionContent = result.ToString(); return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
/// <summary> /// Defines CNTK Function with certain arguments. /// </summary> /// <param name="function">CNTK function</param> /// <param name="prediction">First parameters of the function.</param> /// <param name="target">Second parameters of the function</param> /// <returns></returns> private Function createFunction(EFunction function, Function prediction, Variable target) { switch (function) { case EFunction.BinaryCrossEntropy: return(CNTKLib.BinaryCrossEntropy(prediction, target, function.ToString())); case EFunction.CrossEntropyWithSoftmax: return(CNTKLib.CrossEntropyWithSoftmax(prediction, target, function.ToString())); case EFunction.ClassificationError: return(CNTKLib.ClassificationError(prediction, target, function.ToString())); case EFunction.SquaredError: return(CNTKLib.SquaredError(prediction, target, function.ToString())); case EFunction.RMSError: return(StatMetrics.RMSError(prediction, target, function.ToString())); case EFunction.MSError: return(StatMetrics.MSError(prediction, target, function.ToString())); case EFunction.ClassificationAccuracy: return(StatMetrics.ClassificationAccuracy(prediction, target, function.ToString())); default: throw new Exception($"The '{function}' function is not supported!"); } }
public Swarm(EFunction function, int particles, double fi1, double fi2, double w, double psi, int width, int height) { _fi1 = fi1; _fi2 = fi2; _w = w; _psi = psi; switch (function) { case EFunction.Sphere: F = new Sphere(); break; case EFunction.Griewangk: F = new Griewangk(); break; case EFunction.Rastrigin: F = new Rastrigin(); break; case EFunction.Rosenbock: F = new Rosenbock(); break; } if (Particles != null) Particles.Clear(); else Particles = new List<Particle>(particles); for (int particle = 0; particle < particles; ++particle) Particles.Add(new Particle(width, height)); CreateMap(width, height); }
public static List <Bee> CreateSwarm(EFunction functionType, EBee beeType, int numberOfBees) { List <Bee> swarm = new List <Bee>(); if (beeType == EBee.Employed) { for (int i = 0; i < numberOfBees; i++) { swarm.Add(new Bee(functionType, EBee.Employed)); } } else if (beeType == EBee.Scout) { for (int i = 0; i < numberOfBees; i++) { swarm.Add(new Bee(functionType, EBee.Scout)); } } else if (beeType == EBee.Onlooker) { for (int i = 0; i < numberOfBees; i++) { swarm.Add(new Bee(functionType, EBee.Onlooker)); } } return(swarm); }
static private bool WriteFunction(EFunctionFile eFile, EFunction eFunction) { try { StringBuilder result = new StringBuilder(); StringBuilder argsStringBuilder = new StringBuilder(); List <EArg> segmentsList, mandatoryList, optionalList, formArgList, allArgsList; EArg bodyArg; Logger.LogInfoIfDebugLevel(DebugLevels.Functions | DebugLevels.All, "\tFunction " + eFunction.functionName); eFunction.frontendReturnTypeName = eFunction.returnTypeName; string operation = Helper.GetRESTOperation(eFile, eFunction); if (string.IsNullOrEmpty(operation)) { return(false); } if (!GetFunctionArgs(eFunction, ref argsStringBuilder, out allArgsList, out segmentsList, out mandatoryList, out optionalList, out formArgList, out bodyArg)) { Logger.LogError("unable to get funcion parameters to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(false); } result.Append("\t\tpublic async Task<" + eFunction.frontendReturnTypeName + "> " + eFunction.functionName + "(" + argsStringBuilder.ToString() + ") {"); string functionBody = GetFunctionBody(eFile, eFunction, operation, segmentsList, mandatoryList, optionalList, formArgList, bodyArg); result.Append(functionBody); eFunction.frontendFunctionContent = result.ToString(); return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
public static List <AbstractPSOParticle> CreateSwarm(ETopology topology, EFunction function, EConstrictionFactor constrictionFactor, int particleAmmount) { List <AbstractPSOParticle> swarm = new List <AbstractPSOParticle>(); for (int i = 0; i < particleAmmount; i++) { if (topology == ETopology.Ring) { swarm.Add(new LocalParticle(function, constrictionFactor)); } else if (topology == ETopology.Global) { swarm.Add(new GlobalParticle(function, constrictionFactor)); } else if (topology == ETopology.Focal) { swarm.Add(new FocalParticle(function, constrictionFactor, swarm, i == 0)); } } if (topology == ETopology.Ring) { for (int i = 0; i < swarm.Count; i++) { ((LocalParticle)swarm[i]).LinkSwarm(swarm, i); } } return(swarm); }
public void saveClickProcess(Vector3 pos, EFunction type) { // 檢查資料夾是否存在,不存在則建立 if (!Directory.Exists(GameInfo.DataPath)) { //新增資料夾 Directory.CreateDirectory(GameInfo.DataPath); } string path = Path.Combine(GameInfo.DataPath, "data.csv"); // 檢查檔案是否存在,不存在則建立 StreamWriter writer; if (!File.Exists(path)) { writer = new FileInfo(path).CreateText(); writer.WriteLine("Time, X, Y, Z}, Type"); } else { writer = new FileInfo(path).AppendText(); } // 時間格式化 string time = DateTime.Now.ToString("yyyy-MM-dd@HH-mm-ss-ffff"); string data = string.Format("{0}, {1:F2}, {2:F2}, {3:F2}, {4}", time, pos.x, pos.y, pos.z, type); writer.WriteLine(data); writer.Close(); writer.Dispose(); }
public IEnumerator recordeClickProcess(Vector3 pos, EFunction type) { print("start recordeClickProcess"); url = string.Format("{0}/{1}", server, "ClickProcess.php"); form = new WWWForm(); form.AddField("guid", guid); string time = DateTime.Now.ToString("yyyy-MM-dd@H-mm-ss-ffff"); form.AddField("time", time); form.AddField("x", string.Format("{0}", (int)pos.x)); form.AddField("y", string.Format("{0}", (int)pos.y)); form.AddField("z", string.Format("{0}", (int)pos.z)); form.AddField("type", string.Format("{0}", type)); using (UnityWebRequest www = UnityWebRequest.Post(url, form)) { yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { print(www.error); } else { get_request = www.downloadHandler.text; print("Form upload complete!"); print(get_request); } } print("end recordeClickProcess"); }
public Processor(T lop_res, T rop) { Operation = EOperation.None; Function = EFunction.None; Lop_Res = lop_res; Rop = rop; }
public Processor() { Operation = EOperation.None; Function = EFunction.None; Lop_Res = new T(); Rop = new T(); }
static public string GetRESTOperation(EFunctionFile eFile, EFunction eFunction) { try { string operation = ""; if (eFunction.functionType == FunctionType.GET) { operation = "get"; } else if (eFunction.functionType == FunctionType.POST) { operation = "post"; } else if (eFunction.functionType == FunctionType.PUT) { operation = "put"; } else if (eFunction.functionType == FunctionType.DELETE) { operation = "delete"; } else { Logger.LogError("unable to identify function operation to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(""); } return(operation); } catch (Exception e) { Logger.LogError(e); } return(""); }
static private string GetFunctionBody(EFunctionFile eFile, EFunction eFunction, string operation, List <EArg> segmentsList, List <EArg> mandatoryList, List <EArg> optionalList, List <EArg> formArgList, EArg bodyArg) { try { List <EArg> parametersList = mandatoryList; parametersList.AddRange(optionalList); StringBuilder bodyTxt = new StringBuilder(); bodyTxt.Append("\t\tif(progressBar)progressBar.visible=true;\n"); bodyTxt.Append("\t\tlet rest=base.createRestObj();\n"); bodyTxt.Append("\t\trest.clear();\n"); bodyTxt.Append("\t\trest.setBaseUrl(base.baseURL);\n"); var cSharpClassName = "S" + eFile.frontendClassName.Remove(0, 1); bodyTxt.Append("\t\trest.setRoute('/v" + eFunction.version.ToString() + "/" + cSharpClassName + "/" + eFunction.functionName + "');\n"); bodyTxt.Append("\t\trest.setToken(base.token);\n"); foreach (EArg eArgSegment in segmentsList) { bodyTxt.Append("\t\trest.appendUrlSegment(" + eArgSegment.name + ");\n"); } foreach (EArg eArgParameter in parametersList) { bodyTxt.Append("\t\trest.appendParameter('" + eArgParameter.name + "'," + eArgParameter.name + ");\n"); } if (bodyArg != null) { bodyTxt.Append("\t\trest.setBody(JSON.stringify(" + bodyArg.name + "));\n"); } bodyTxt.Append("\t\treturn rest." + Helper.GetRESTOperationForQML(eFile, eFunction, true) + "(progressBar);\n"); bodyTxt.Append("\t}"); return(bodyTxt.ToString()); } catch (Exception e) { Logger.LogError(e); } return(""); }
private void RegisterCustomNodeInstanceForLateInitialization( EFunction node, Guid id, string name) { var disposed = false; Action <CustomNodeInfo> infoUpdatedHandler = null; infoUpdatedHandler = newInfo => { if (newInfo.FunctionId == id || newInfo.Name == name) { CustomNodeWorkspaceModel foundWorkspace; if (TryGetFunctionWorkspace(newInfo.FunctionId, out foundWorkspace)) { node.ResyncWithDefinition(foundWorkspace.CustomNodeDefinition); RegisterCustomNodeInstanceForUpdates(node, foundWorkspace); InfoUpdated -= infoUpdatedHandler; disposed = true; } } }; InfoUpdated += infoUpdatedHandler; node.Disposed += (args) => { if (!disposed) { InfoUpdated -= infoUpdatedHandler; } }; }
//Ex from Typescript: [RestInPeacePost("ECaminhao GetByID(segment number id, mandatory number age, optional string bla, body string oi)")] static private bool WriteFunction(EFunctionFile eFile, EFunction eFunction) { try { StringBuilder result = new StringBuilder(); StringBuilder argsStringBuilder = new StringBuilder(); List <EArg> segmentsList, mandatoryList, optionalList, formArgList, allArgsList; EArg bodyArg; Logger.LogInfo("\tFunction " + eFunction.functionName); string functionName = Char.ToLowerInvariant(eFunction.functionName[0]) + eFunction.functionName.Substring(1); string operation = Helper.GetRESTOperation(eFile, eFunction); if (string.IsNullOrEmpty(operation)) { return(false); } if (!GetFunctionArgs(eFunction, ref argsStringBuilder, out allArgsList, out segmentsList, out mandatoryList, out optionalList, out formArgList, out bodyArg)) { Logger.LogError("unable to get funcion parameters to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(false); } result.Append("\tasync "); result.Append(functionName); result.Append("("); result.Append(argsStringBuilder.ToString()); result.Append("):Promise<"); result.Append(AngularWatcher.ConvertToAngularTypeName(eFunction.returnTypeName)); result.Append(">{\n"); string functionBody = GetFunctionBody(eFile, eFunction, operation, segmentsList, mandatoryList, optionalList, formArgList, bodyArg); result.Append(functionBody); eFunction.frontendFunctionContent = result.ToString(); return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
public static bool MatchAndNameParameters(List <Variable> callerParameters, EFunction subject) { // invalid call if (callerParameters == null || subject == null) { return(false); } // first, check the number of parameters if (callerParameters.Count != subject.Parameters.Count) { return(false); } // match and name all parameters by type, in order of appearance var match = true; for (var i = 0; i < callerParameters.Count; i++) { if (callerParameters[i].Type != subject.Parameters[i].Type) { match = false; break; } callerParameters[i].Name = subject.Parameters[i].Name; } return(match); }
/// <summary> /// Creates a new Custom Node Instance. /// </summary> /// <param name="id">Identifier referring to a custom node definition.</param> /// <param name="name"> /// Name for the custom node to be instantiated, used for error recovery if /// the given id could not be found. /// </param> /// <param name="def"> /// Custom node definition data /// </param> /// <param name="info"> /// Custom node information data /// </param> /// <returns>Custom Node Instance</returns> public EFunction CreateCustomNodeInstance( Guid id, string name, CustomNodeDefinition def, CustomNodeInfo info) { if (info == null) { // Couldn't find the workspace at all, prepare for a late initialization. Log(Properties.Resources.UnableToCreateCustomNodeID + id + "\"", WarningLevel.Moderate); info = new CustomNodeInfo(id, name ?? "", "", "", ""); } if (def == null) { def = CustomNodeDefinition.MakeProxy(id, info.Name); } var node = new EFunction(def, info.Name, info.Description, info.Category); CustomNodeWorkspaceModel workspace = null; if (loadedWorkspaceModels.TryGetValue(id, out workspace)) { RegisterCustomNodeInstanceForUpdates(node, workspace); } else { RegisterCustomNodeInstanceForLateInitialization(node, id, name); } return(node); }
public override EVariable Solve(EScope scope) { EFunction toRun = scope.GetFunction(callFunc.ToString()); EVariable output = toRun.Exec(scope, arguments); return(output); }
static private bool GetFunctionArgs(EFunction eFunction, ref StringBuilder argsStringBuilder, out List <EArg> allArgsList, out List <EArg> segmentsList, out List <EArg> mandatoryList, out List <EArg> optionalList, out List <EArg> formArgList, out EArg bodyArg) { segmentsList = null; mandatoryList = null; optionalList = null; formArgList = null; allArgsList = new List <EArg>(); bodyArg = null; try { //orderby then to linq nao funciona para mesmo campo bodyArg = Helper.GetBodyArg(eFunction.argsList); segmentsList = Helper.GetSegmentsArgs(eFunction.argsList); mandatoryList = Helper.GetMandatoryArgs(eFunction.argsList); optionalList = Helper.GetOptionalArgs(eFunction.argsList); formArgList = Helper.GetFormArgs(eFunction.argsList); if (bodyArg != null) { allArgsList.Add(bodyArg); } if (segmentsList.Any()) { allArgsList.AddRange(segmentsList); } if (mandatoryList.Any()) { allArgsList.AddRange(mandatoryList); } if (optionalList.Any()) { allArgsList.AddRange(optionalList); } if (formArgList.Any()) { allArgsList.AddRange(formArgList); } for (int i = 0; i < allArgsList.Count; i++) { EArg eArg = allArgsList.ElementAt(i); argsStringBuilder.Append(eArg.typeName); argsStringBuilder.Append(" "); argsStringBuilder.Append(eArg.name); if (!string.IsNullOrEmpty(eArg.defaultValue)) { eArg.defaultValue = eArg.defaultValue.Replace("\'", "\""); //if(eArg.defaultValue=="''")argsStringBuilder.Append("=\"\""); argsStringBuilder.Append("=" + eArg.defaultValue); } if (i < (allArgsList.Count - 1)) { argsStringBuilder.Append(", "); } } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
//Ex from Typescript: [RestInPeacePost("ECaminhao GetByID(segment number id, mandatory number age, optional string bla, body string oi)")] static private bool WriteFunction(EFunctionFile eFile, EFunction eFunction) { try { StringBuilder result = new StringBuilder(); StringBuilder argsStringBuilder = new StringBuilder(); List <EArg> segmentsList, mandatoryList, optionalList, formArgList, allArgsList; EArg bodyArg; Logger.LogInfo("\tFunction " + eFunction.functionName); string functionName = Char.ToLowerInvariant(eFunction.functionName[0]) + eFunction.functionName.Substring(1); string operation = Helper.GetRESTOperation(eFile, eFunction); if (string.IsNullOrEmpty(operation)) { return(false); } if (!GetFunctionArgs(eFunction, ref argsStringBuilder, out allArgsList, out segmentsList, out mandatoryList, out optionalList, out formArgList, out bodyArg)) { Logger.LogError("unable to get funcion parameters to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(false); } result.Append("function "); result.Append(functionName); string args = argsStringBuilder.ToString(); if (!isForTypescriptApp) { if (args.Length > 0) { result.Append("(progressBar, callback, "); } else { result.Append("(progressBar, callback"); //nao tem argumento } } else { if (args.Length > 0) { result.Append("(progressBar, "); } else { result.Append("(progressBar"); //nao tem argumento } } result.Append(args); result.Append(") {\n"); string functionBody = GetFunctionBody(eFile, eFunction, operation, segmentsList, mandatoryList, optionalList, formArgList, bodyArg); result.Append(functionBody); eFunction.qmlFunctionContent = result.ToString(); return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
public void FunctionSet(int newfunc) { try { Function = (EFunction)newfunc; } catch { throw new ArgumentException(); } }
private void ProcessExpression(string name, EFunction function, string parameter, out string expression, out EDataBaseType expressionDataType) { expression = "item." + name; expressionDataType = QueryMetadata.GetLeftDataType(Data.Entity, name); if (QueryMetadata.Functions.ContainsKey(function)) { var functionInfo = QueryMetadata.Functions[function]; expression = string.Format(functionInfo.Template, expression, parameter); expressionDataType = functionInfo.ReturnType; } }
public static List <FireflyParticle> CreateSwarm(EFunction functionType) { List <FireflyParticle> swarm = new List <FireflyParticle>(); for (int i = 0; i < Parameters.PARTICLE_AMOUNT; i++) { swarm.Add(new FireflyParticle(functionType)); } return(swarm); }
public void SetFunction(string name, EFunction program) { try { functions.Add(name, program); } catch { throw new ELangException("The function " + name + " has already been declared"); } }
public FireflyParticle(EFunction functionType) { Alpha = 1.0d; Position = new double[Parameters.DIMENSION_AMOUNT]; if (function == null) { FireflyParticle.functionType = functionType; function = AbstractFunction.InstanceFunction(functionType); } }
public Bee(EFunction functionType, EBee beeType) { Position = new double[Parameters.DIMENSION_AMOUNT]; this.beeType = beeType; if (function == null) { FoodSourceList = new List <FoodSource>(); Bee.functionType = functionType; function = AbstractFunction.InstanceFunction(functionType); } }
public AbstractPSOParticle(EFunction functionType, EConstrictionFactor constrictionType) { Position = new double[Parameters.DIMENSION_AMOUNT]; Velocity = new double[Parameters.DIMENSION_AMOUNT]; if (function == null || constriction == null) { AbstractPSOParticle.functionType = functionType; AbstractPSOParticle.constrictionType = constrictionType; function = AbstractFunction.InstanceFunction(functionType); constriction = AbstractConstrictionFactor.InstanceFunction(constrictionType); } }
public void clickProcess(Vector3 pos, EFunction type) { string url = "140.122.91.200/ScreenShot.php"; WWWForm form = new WWWForm(); string time = DateTime.Now.ToString("yyyy-MM-dd@H-mm-ss-ffff"); form.AddField("time", time); form.AddField("time", time); form.AddField("time", time); form.AddField("time", time); StartCoroutine(Upload(url, form)); }
public FocalParticle(EFunction functionType, EConstrictionFactor constrictionType, List <AbstractPSOParticle> swarm, bool isFocalParticle) : base(functionType, constrictionType) { this.swarm = swarm; this.IsFocalParticle = isFocalParticle; foreach (AbstractPSOParticle abs in swarm) { if (((FocalParticle)abs).IsFocalParticle) { focalParticle = abs; break; } } }
public static void SaveToFile2(ETopology top, EFunction fun, EConstrictionFactor cons, List <List <Double> > outputSamples, int id) { List <String> stringList = new List <string>(); stringList.Add("Iterations\tFitness (Avergage from 30 samples)"); stringList.Add("{"); for (int i = 0; i < Parameters.SAMPLE_COUNT; i++) { stringList.Add((outputSamples[i][outputSamples[i].Count - 1]).ToString().Replace(',', '.') + ","); } stringList.Add("}"); System.IO.File.WriteAllLines(@"" + top + ", " + fun + ", " + cons + ", " + id + ".txt", stringList.ToArray()); }
static private bool AnalyseFile(string path) { try { if (!File.Exists(path)) { return(true); } FileInfo fileInfo = new FileInfo(path); if (fileInfo.Name.StartsWith("E")) { return(true); //entity } string fullContent = File.ReadAllText(path); if (fullContent.Contains("public enum")) { return(true); //enum } IEnumerable <string> linesList = fullContent.Split('\n'); EFunctionFile eFile = new EFunctionFile(); eFile.csharpFileName = fileInfo.Name.Replace(".cs", String.Empty); eFile.functionList = new List <EFunction>(); if (fullContent.Contains("[RestInPeace")) { Logger.LogInfoIfDebugLevel(DebugLevels.Files | DebugLevels.All, "\t" + eFile.csharpFileName); } for (int l = 0; l < linesList.Count(); l++) { string lineContent = linesList.ElementAt(l); if (!lineContent.Contains("[RestInPeace")) { continue; } EFunction eFunction = AnalyseTypeSyncFunction(fileInfo.Name, lineContent, l + 1); if (eFunction == null) { return(false); } eFile.functionList.Add(eFunction); } if (eFile.functionList.Count > 0) { Globals.backendControllerFiles.Add(eFile); } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static void Main(string[] args) { System.Console.WriteLine("The problem of the algebraic interpolation."); Interpolation i = new Interpolation(); Function f = new EFunction(); float a = 0.4f; float b = 1; int m = 15; int n = 5; System.Console.Write("Function: "); f.Print(); System.Console.WriteLine("Segment: [{0}, {1}]", a, b); System.Console.WriteLine("Params: m = {0}, n = {1}", m, n); i.Func = f; i.Init(m, n, a, b); float fx; while (true) { System.Console.WriteLine("What method you wanna use? (0 - Lagrange, 1 - Newton)"); string val = System.Console.ReadLine(); System.Console.WriteLine("Input X"); float x = Convert.ToSingle(System.Console.ReadLine(), System.Globalization.CultureInfo.InvariantCulture); if (Convert.ToInt32(val) == 0) { fx = i.Calc(x, new LagrangeMethod()); } else { fx = i.Calc(x, new NewtonMethod()); } System.Console.WriteLine("Pn(x) = {0}", (double)fx); System.Console.WriteLine("efn(x) = {0}", Math.Abs((float)f.f(x) - (float)fx)); } System.Console.ReadKey(); }
/// <summary> /// Constructs a new instance. /// </summary> /// <param name="funcSel">which operation the ALU is supposed to carry out</param> /// <param name="arithMode">signedness of operands/result</param> /// <param name="pipelineDepth">desired latency</param> /// <param name="awidth">width of first (or sole) operand</param> /// <param name="bwidth">width of second operand</param> /// <param name="rwidth">width of result</param> /// <exception cref="ArgumentOutOfRangeException">if parameter is invalid or inconsistency between parameters was detected</exception> public ALU(EFunction funcSel, EArithMode arithMode, int pipelineDepth, int awidth, int bwidth, int rwidth) { Contract.Requires<ArgumentOutOfRangeException>(pipelineDepth >= 0, "Pipeline depth must be non-negative."); Contract.Requires<ArgumentOutOfRangeException>(awidth >= 1, "Operand width A must be positive."); Contract.Requires<ArgumentOutOfRangeException>(funcSel.IsUnary() || bwidth >= 1, "Operand width B must be positive."); Contract.Requires<ArgumentOutOfRangeException>(funcSel == EFunction.Compare || rwidth >= 1, "Result width must be positive"); Contract.Requires<ArgumentOutOfRangeException>(funcSel == EFunction.Add || funcSel == EFunction.Mul || funcSel == EFunction.Neg || funcSel == EFunction.Sub || awidth == bwidth, "Operand sizes must be equal for this kind of operation."); Contract.Requires<ArgumentOutOfRangeException>(funcSel == EFunction.Add || funcSel == EFunction.Compare || funcSel == EFunction.Mul || funcSel == EFunction.Neg || funcSel == EFunction.Sub || rwidth == awidth, "Result and operand sizes must be equal for this kind of instruction."); FuncSel = funcSel; ArithMode = arithMode; PipelineDepth = pipelineDepth; if (funcSel == EFunction.Compare) rwidth = 6; AWidth = awidth; BWidth = bwidth; RWidth = rwidth; _opResult = new SLVSignal(rwidth) { InitialValue = StdLogicVector._0s(rwidth) }; if (pipelineDepth >= 3) { // If pipeline depth > 0, the operand inputs will be registered. // Thus, the post pipeline must be reduced by one stage. _pipe = new RegPipe(Math.Max(0, pipelineDepth - 1), rwidth); if (FuncSel == EFunction.Compare) { _pipeOut = new SLVSignal(rwidth) { InitialValue = StdLogicVector._0s(rwidth) }; Bind(() => { _pipe.Clk = Clk; _pipe.Din = _opResult; _pipe.Dout = _pipeOut; }); } else { Bind(() => { _pipe.Clk = Clk; _pipe.Din = _opResult; _pipe.Dout = R; }); } } _transactor = new ALUTransactor(this); }
private void radioButtonFunction_CheckedChanged(object sender, EventArgs e) { if (radioButtonSphere.Checked) { functionType = EFunction.Sphere; return; } if (radioButtonGriewangk.Checked) { functionType = EFunction.Griewangk; return; } if (radioButtonRastrigin.Checked) { functionType = EFunction.Rastrigin; return; } if (radioButtonRosenbock.Checked) { functionType = EFunction.Rosenbock; return; } }