Hy,
I have the below Jacobi method implementation in Scilab, but I receaive errors,
function [x]= Jacobi(A,b)
[n m] = size (A); // determinam marimea matricei A
//we check if the matrix is quadratic
if n<>m then
error('Matricea ar trebui sa fie patratica');
abort;
end
we initialize the zeros matrix
x = zeros(n,1) // matrice cu zerouri x = [0, 0 ... 0]
// initializarea variabilelor
Itmax=1000.; //numar maxim de iteratii
eps=0.0000000000000001 // toleranta maxima
nrit=0;
ready=0;
while (ready==0)
for i=1:n
s=0
for j=1:n
if i<>j then
s=A(i,j)+x(j);
end
end
y(i)=(1/A(i,i))*(b(i)-s);
end
abso = norm(x(1),y(1));
for i=2:n
if abso<norm(x(i),y(i)) then
abso=norm(x(i),y(i));
end
end
nrit=nrit+1;
if((nrit==Itmax)|(abso<eps)) then
ready=1;
end
x=y;
end
for i=1:n
disp(y(i),'Rezidurile medii');
end
x
What is wrong with it!
Sincerly,
I don't know what errors you get and I noticed there are some issues in the implementation as well, but you can use the following code which works fine:
Jacobi Alghoritm
function [x]= Jacobi(A,b)
[n m] = size (A); // determinam marimea matricei A
if n<>m then
error('Matricea ar trebui sa fie patratica');
end
// initializarea variabilelor
x = zeros(n,1) // matrice cu zerouri x = [0, 0 ... 0]
Itmax=1000.; //numar maxim de iteratii
eps=0.0000000000000001 // toleranta maxima
nrit=0;
ready=0;
while (ready==0)
for i=1:n
s=0
for j=1:n
if i<>j then
s=s+A(i,j)*x(j);
end
end
y(i)=(1/A(i,i))*(b(i)-s);
end
abso = abs(x(1)-y(1));
for i=2:n
if abso<abs(x(i)-y(i)) then
abso=abs(x(i)-y(i));
end
end
nrit=nrit+1;
if((nrit==Itmax)|(abso<eps)) then
ready=1;
end
x=y;
end
Let's say you saved this in a file at ~/Jacobi.sci
Usage (in Scilab)
-->exec('~/Jacobi.sci', -1)
-->Jacobi([3,-1,-1;-1,3,1;2,1,4],[1,3,7])
ans =
1.
1.
1.
Related
I have made a program for obtaining a list of prime numbers in ADA and using the following online compiler:
https://rextester.com/l/ada_online_compiler
My code is the following:
--GNAT 8.3.0
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO;
procedure prime is
function isPrime(n:in Integer) return Boolean is
begin
for i in 2..n loop
if n mod i=0 then
return False;
end if;
end loop;
return True;
end isPrime;
begin
for i in 1..100 loop
if isPrime(i)=True then
Ada.Text_IO.Put_Line(Integer'Image(i));
end if;
Ada.Text_IO.Put_Line(Integer'Image(i));
end loop;
end prime;
And instead of printing a list of primes it only print 1. I have program the same code in C and no problem at all.
Your for loop in isPrime() checks every value higher than one as "n mod n = 0" which will cause you to return false for every value higher than 1. Change the for loop condition to
for i in 2..(n-1) loop
and work from there
Expanding on Jere's approach, several simple primality tests will simplify the divisibility test in the isPrime loop:
The only even prime, 2, can be handled immediately:
if N = 2 then
return True;
end if;
All remaining even numbers can be eliminated:
if N mod 2 = 0 then
return False;
end if;
This leaves odd numbers in the range 3 .. √N to check:
for i in 3 .. Positive (Sqrt (Float (N))) loop
if N mod i = 0 then
…
end if;
end loop;
It is even better by defining a Prime_Number type containing prime numbers.
subtype Prime_Number is Positive range 2 .. Positive'Last with
Dynamic_Predicate => (for all I in 2 .. (Prime_Number / 2)
=> (Prime_Number mod I) /= 0);
Then, use the code segment below to print out all prime numbers between 2 .. 100 range.
for Index in Positive range 2 .. 100 loop
if Index in Prime_Number then
Put_Line ("Prime number: " & Index'Image);
end if;
end loop;
I'm trying to do a solver for equations. When I run the code the X variable appears to be undefined, but it prints out perfectly. What am I missing?
I should give the program some numbers, than operations as Macros and it should create an outer product matrix of the operations applied.
function msu()
print("Insert how many values: ")
quantity = parse(Int64, readline())
values = []
for i in 1:quantity
println("x$i")
num1 = parse(Float64, readline())
push!(values, num1)
end
println(values)
print("How many operations? ")
quantity = parse(Int64, readline())
ops = []
for i in 1:quantity
push!(ops, Meta.parse(readline()))
end
mat = zeros((quantity, quantity))
for i in 1:length(mat)
sum = 0
for j in 1:length(values)
# here begins problems, the following prints are for debugging purpose
print(length(values))
func = Meta.parse("$(ops[convert(Int64, ceil(j / quantity))]) * $(ops[convert(Int64, j % quantity)])")
print(func)
x = values[j]
println(x)
sum += eval(func)
end
mat[i] = sum
end
println(mat)
end
msu()
The original code was in Spanish, if you find any typo it's probably because I skipped a translation.
I'm using NLopt for a constrained maximization problem. Regardless of the algorithm or start values, the optimization program is force stopped even before the first iteration (or so I assume because it gives me the initial value). I've attached my code here. I'm trying to find probabilities attached to a grid such that a function is maximized under some constraints. Any help is appreciated.
uk = x -> x^0.5
function objective(u,p,grd)
-p'*u.(grd)
end
function c3(grd,p)
c =[]
d =[]
for i=1:length(grd)
push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
end
return append!(d-c,-p)
end
function c4(grd,p)
return (grd .* p)-quadgk(x,0,1)
end
grd = n -> collect(0:1/n:1)
opt = Opt(:LD_SLSQP,11)
inequality_constraint!(opt, p -> c3(grd(10),p))
inequality_constraint!(opt, p -> -p)
equality_constraint!(opt, p -> sum(p)-1)
equality_constraint!(opt, p -> c4(grd(10),p))
opt.min_objective = p -> objective(-uk, p, grd(10))
k = push!(ones(11)*(1/11))
(minf,minx,ret) = optimize(opt, k)
I'm not a julia developer, but I only know this, if you need exit before complete the loop for is not your best choice, you need do a while with a sentinel variable.
here you have an article that explain you how while with sentinels works
and here you have a julia example changing your for to a while with a sentinel that exit after the third loop
i = 1
third = 0
while i < length(grd) && third != 1
# of course you need change this, it is only an example that will exit in the 3 loop
if i == 3
third = 1
end
push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
i += 1
end
I am new to Fortran and I have the following code, it basically solves a simple quadratic equation and output the solutions
!solving ax^2 + bx + c = 0
program output
implicit none
real :: a,b,c
character :: response
do
print*, 'Enter three coefficients a,b and c'
read *, a,b,c
call quad(a,b,c)
print*, 'Press Y to continue. Anykey for otherwise'
read *, response
if ( response /= 'y' .and. response /= 'Y') stop
end do
end program output
!Function to calculate Xs
subroutine quad(a,b,c)
implicit none
real :: a,b,c,xplus, xminus
xplus = ((-b)+sqrt((b**2)-(4*a*c)))/(2*a)
xminus = ((-b)-sqrt((b**2)-(4*a*c)))/(2*a)
if (xplus == xminus) then
print*, 'There exists 1 root only: '
write(*,12) xplus
12 format(2f10.2)
else
print*, 'Solutions of quadratic equation are'
write(*,10) xplus, xminus
10 format(1f10.5)
end if
end subroutine quad
This works. However, how would I go about with complex solutions. I.e, how would this line change, to make the format for complex numbers.
10 format(1f10.5)
Thank you so much.
I'm trying to populate an array of functions in Julia. A minimal example is
function nice()
i=1
while true
f() = i
produce(f)
i+=1
end
end
ye = Task(() -> nice())
funcs = Function[]
for i in [1:2]
push!(funcs,consume(ye))
println("Why does this not stay the same???")
println(funcs[1]())
end
The problem is that funcs[1] changes from the one that returns 1 to the one that returns 2! Please help me out!
This solved it. I needed a let command and and f=()->j statement
function nice()
i=1
while true
let j=i
f=()->j
produce(f)
end
i+=1
end
end
ye = Task(() -> nice())
funcs = Function[]
for k in [1:2]
push!(funcs,consume(ye))
end
println(funcs[1]())
println(funcs[2]())