Hilbert Matrix
Last Updated :
01 Dec, 2022
A Hilbert Matrix is a square matrix whose each element is a unit fraction.
Properties:
- It is a symmetric matrix.
- Its determinant value is always positive.
Examples:
Input : N = 2
Output : 1 0.5
0.5 0.33
Input : N = 3
Output : 1.0000 0.5000 0.3333
0.5000 0.3333 0.2500
0.3333 0.2500 0.2000
Mathematically, Hilbert Matrix can be formed by the given formula:
Let H be a Hilbert Matrix of NxN.
Then
H(i, j) = 1/(i+j-1)
Below is the basic implementation of the above formula.
C++
#include <bits/stdc++.h>
using namespace std;
void printMatrix( int n)
{
float H[n][n];
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
H[i][j] = ( float )1.0 /
((i + 1) + (j + 1) - 1.0);
}
}
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++)
cout << H[i][j] << " " ;
cout << endl;
}
}
int main()
{
int n = 3;
printMatrix(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void printMatrix( int n)
{
float H[][] = new float [n][n];
for ( int i = 0 ; i < n; i++)
{
for ( int j = 0 ; j < n; j++)
{
H[i][j] = ( float ) 1.0 /
((i + 1 ) + (j + 1 ) -
( float ) 1.0 );
}
}
for ( int i = 0 ; i < n; i++)
{
for ( int j = 0 ; j < n; j++)
System.out.print(H[i][j] + " " );
System.out.println();
}
}
public static void main (String[] args)
{
int n = 3 ;
printMatrix(n);
}
}
|
Python3
def printMatrix(n):
H = [[ None for _ in range (n)] for __ in range (n)]
for i in range (n):
for j in range (n):
H[i][j] = 1 / ((i + 1 ) + (j + 1 ) - 1 )
for i in range (n):
print ( * H[i])
n = 3
printMatrix(n)
|
C#
using System;
class GFG
{
static void printMatrix( int n)
{
float [,] H = new float [n, n];
for ( int i = 0; i < n; i++)
{
for ( int j = 0; j < n; j++)
{
H[i, j] = ( float )1.0 /
((i + 1) + (j + 1) -
( float )1.0);
}
}
for ( int i = 0; i < n; i++)
{
for ( int j = 0; j < n; j++)
Console.Write(H[i, j] + " " );
Console.WriteLine( "" );
}
}
public static void Main()
{
int n = 3;
printMatrix(n);
}
}
|
Javascript
function printMatrix(n)
{
let H = new Array(n);
for ( var i = 0; i < n; i++) {
H[i] = new Array(n);
for ( var j = 0; j < n; j++) {
H[i][j] = 1.0 /
((i + 1) + (j + 1) - 1.0);
}
}
for ( var i = 0; i < n; i++) {
for ( var j = 0; j < n; j++)
process.stdout.write(H[i][j] + " " );
process.stdout.write( "\n" );
}
}
n = 3;
printMatrix(n);
|
Output
1 0.5 0.333333
0.5 0.333333 0.25
0.333333 0.25 0.2
Time complexity: O(n2)
Auxiliary space: O(n2)
Share your thoughts in the comments
Please Login to comment...