数值计算——施密特正交化

施密特正交化单位正交基C++代码


使用施密特正交化得出单位正交基的完整代码

#include <time.h>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <math.h>

using namespace std;
const int N = 5000;
typedef double Type;

Type A[N][N];

void schmidt(Type A[][N], int n, int k, int l); /*施密特正交化*/
void Print(Type L[][N], int n);//输入
void united(Type A[][N], int n);//向量单位化
int Random(int start, int end);/*随机数*/

int Random(int start, int end)
{
	int dis = end - start;
	return rand() % dis + start;
}
void Print(Type L[][N], int n)
{
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
			cout << L[i][j] << " ";
		cout << endl;
	}
	cout << endl;
}

void united(Type A[][N], int n) {
	vector<Type> B;
	Type y = 0;
	for (int i = 0; i < n; i++) {
		for (int l=0;l<n;l++)
			y += A[i][l] * A[i][l];
		y = sqrt(y);
		B.push_back(y);
	}
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			A[i][j] /= B[i];
		}
	}
	B.clear();
}
void schmidt(Type A[][N],int n,int k,int l) {//施密特正交化
	vector<Type> B;
	double num = 0;
	int t=0;
	//(a.b)/|b|
	for (int i = 0; i < n; i++) {
		t += A[k][i] * A[l][i];
	}
	for (int i = 0; i < n; i++) {
		Type y=0;
		y = t * A[l][i];
		B.push_back(y);
	}
	for (int i = 0; i < n; i++) {
		num += A[l][i] * A[l][i];
	}
	for (int i = 1; i < n ; i++) {
			A[k][i] -= (B[i] / num);
	}
	B.clear();
	if (l+1 < k) {
		schmidt(A, n, k, l + 1);
	}
	else if (k + 1 < n) {
		schmidt(A,  n, k + 1, 0);
	}
}

int main()
{
	srand((int)time(0));
	double duration;
	clock_t start, finish;
	int n;
	cout << "输入矩阵大小";
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++) {
			/*if (i == j) {
				A[i][i] = 1;
				continue;
			}
			A[i][j] = 0;*/
			A[i][j] = Random(0, 10);
		}
	}
	//Print(A, n);
	start = clock();//获取当前时间
	schmidt(A, n,1,0);
	//Print(A, n);
	united(A, n);
	//Print(A, n);
	printf("完成!");
	finish = clock();//获取当前时间
	duration = (double)(finish - start);//计算程序运行时间
	cout << "时间为:";
	cout << duration << endl;
	return 0;
}

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小佈要早睡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值