本文介绍了线性功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我需要编写一个分段函数,可以将百分比从95到65并将其转换为gpa值。技巧是,95 = 4.0,94 = 3.9,93 = 3.8,92 = 3.7,并且每个百分点继续减少.1,直到它达到65 = 1.0。如果不手动输入大量的其他内容,我就会变得难以理解。 $(#theButton ).click(function(){ var perc = $(#perc)。val(); var hardperc =(1 +((perc-65)/ 10)); perc = parseFloat(perc); 解决方案如果你想要简单的线性归一化,那么下面的函数应该可以做到。不是使用重复的逻辑或条件,你可以使用一些数学。 //可重用的线性规范化functionconst linearNormalize =(fromMin,fromMax,toMin,toMax)=> value => {//规范化输入值var pct =(value - fromMin)/(fromMax - fromMin); var normalized = pct *(toMax - toMin)+ toMin; // Cap输出到min / max if(normalized> toMax)回到Max; if(normalized< toMin)返回Min; return normalized;} //包装函数与您的特定inputsConst gradeToGpa = linearNormalize(65,95,1.0,4.0); console.log(gradeToGpa(78)); 使用 Scott Sauyet 咖喱功能建议: const linearNormalize =(fromMin,fromMax,toMin,toMax)=> value => {var pct =(value - fromMin)/(fromMax - fromMin); var normalized = pct *(toMax - toMin)+ toMin; if(normalized> toMax)返回到; if(normalized< toMin)返回Min; return normalized;} const gradeToGpa = linearNormalize(65,95,1.0,4.0); console.log(gradeToGpa(78)); I need to write a piecewise function that can take a percentage from 95 to 65 and convert that to a gpa value. The trick is, 95=4.0, 94=3.9, 93=3.8, 92=3.7, and that continues decreasing by .1 per percentage point until it hits 65=1.0. I'm becoming stumped how to code this without manually entering in a ton of else-ifs.$("#theButton").click(function() { var perc = $("#perc").val(); var hardperc = (1+((perc-65)/10)); perc = parseFloat(perc); 解决方案 If you want simple linear normalization then the following function should do the trick. Rather than use repeated logic or conditionals, you can just use some math.//Reusable Linear Normalization functionconst linearNormalize = (fromMin, fromMax, toMin, toMax) => value => { //Normalize the input value var pct = (value - fromMin) / (fromMax - fromMin); var normalized = pct * (toMax - toMin) + toMin; //Cap output to min/max if (normalized > toMax) return toMax; if (normalized < toMin) return toMin; return normalized;}//Wrapper function with your specific inputsconst gradeToGpa = linearNormalize(65, 95, 1.0, 4.0);console.log(gradeToGpa(78));With Scott Sauyet's curried functions suggestion:const linearNormalize = (fromMin, fromMax, toMin, toMax) => value => { var pct = (value - fromMin) / (fromMax - fromMin); var normalized = pct * (toMax - toMin) + toMin; if (normalized > toMax) return toMax; if (normalized < toMin) return toMin; return normalized;}const gradeToGpa = linearNormalize(65, 95, 1.0, 4.0);console.log(gradeToGpa(78)); 这篇关于线性功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-01 04:35