Unity主要是3D视景仿真,但是如果需要建立数学模型来进行计算的仿真,则需要一些数学包来辅助。
当然了,你也可以用高数来手撸一个,不过本文不做讨论。
====以二元线性回归为例====
1、mathnet的下载地址

2、包的配置和脚本挂载

?
3、脚本的实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MathNet.Numerics; //数学包,下载的网址:https://github.com/mathnet/mathnet-numerics
using System;
public class mathnet : MonoBehaviour
{
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
TestRegression();
}
}
/// <summary>
/// 线性回归:二元回归
/// </summary>
/// <param name="X">X变量系列</param>
/// <param name="Y">Y变量系列</param>
/// <returns>返回值,元组tuple(b=常数,k=系数)</returns>
Tuple<double,double> Regression(double[] X,double[] Y)
{
Tuple<double, double> res = new Tuple<double, double>(0, 0);
res = Fit.Line(X, Y);
double b = res.Item1;
double k = res.Item2;
return res;
}
/// <summary>
/// 测试二元线性回归
/// </summary>
void TestRegression()
{
double[] X = new double[] { 6, 5, 4, 3, 2, 2, 1 };
double[] Y = new double[] { 1, 2, 3, 4, 5, 6, 7 };
var rtn = Regression(X,Y);
var b = rtn.Item1;
var k = rtn.Item2;
Debug.Log($"X系数为:{k},常数为:{b}");
}
}
4、excel的计算的结果
(1)原始数据

?(2)计算结果

?
?5、Unity计算的结果

6、excel和unity的计算结果对比

?
?
|