Below is the code for my program. I'm attempting to find the value of the integral of 1/ln(x), and then evaluate the integral from 0 to x, with this as the integrand. I'm not exactly sure what I'm doing wrong, but I am quite new to Scilab.
t = input("t");
x=10; while x<t, x=x+10,
function y=f(x), y=(1/(log (x))), endfunction
I=intg(2,x,f);
function z=g(x), z=I, endfunction
W = intg(0,x,z);
W
end
I'm not entirely sure on what you are trying to achieve, but I reformatted your code and added some suggestions to documentation.
Maybe it will help you in finding the answer.
While loop
You can convert your while loop to a for loop
Your code
x=10;
while x<t
x=x+10
//some code
end
Could be
for x=10:10:t
//some code
end
Functions
In your code, you redeclare the two functions every single iteration of the while loop. You could declare them outside the while loop and call them inside the loop.
Reformatted
t = input("Please provide t: ");
// The function of 1/ln(x)
function y=f(x), y=1/log(x), endfunction
// Every time g(x) is called the current value of I is returned
function z=g(x), z=I, endfunction
for x=10:10:t
//Find definite integral of function f from 2 to x
I = intg(2,x,f);
//Find definite integral of I from 0 to x
W = intg(0,x,g);
disp( string(W) );
end
I know the question is porbably outdated; but the topic is still active. And I was looking for a code with double integral.
Here, it looks strange to use "intg" just to calculate the area of the rectangle defined by its diagonal ((0,0), (x,I)): the result is just x*I...
May be the initial aim was to consider "I" as a function of "x" (but in this case there is a convergence problem at x=1...); so restricting the integration of "I" to something above 1 gives the following code:
x=10:10:100;W2=integrate('integrate(''1/log(x2)'',''x2'',2,x1)','x1',1.001,x);
Note the use of integration variables x1 and x2, plus the use of quotes...
Related
I have been developing a Scilab function where I need to have persistent variable of the matrix type. Based on my similar question I have chosen the same approach. Below is the code I have used for test of this approach.
function [u] = FuncXYZ(x)
global A;
global init;
if init == 0 then
init = 1;
A = eye(4, 4);
endif
u = A(1, 1);
endfunction
As soon as I have integrated the function inside my Xcos simulation I have been surprised that I see "0" at the output of the scifunc_block_m.
Nevertheless I have found that in case I use below given command for "return" from the function
u = A(3, 3);
the function returns really the expected "1". Additionaly if I take a look at the Variable Browser on the top right corner of the Scilab window I can't se the expected A 4x4 item. It seems that I am doing something wrong.
Can anybody give me an advice how to define a persistent variable of the matrix type inside the Scilab function?
Thanks in advance for any ideas.
Global variables are by default initialized with an empty matrix. Hence, you should detect first call with isempty()
function [u] = FuncXYZ(x)
global A;
global init;
if isempty(init)
init = 1;
A = eye(4, 4);
end
u = A(1, 1);
endfunction
BTW, your code is incorrect, there is no endif in Scilab.
I am working with a program which includes many function calls inside a for loop. For short, it is something like this:
function something()
....
....
timer = zeros(NSTEP);
for it = 1:NSTEP # time steps
tic = time_ns();
Threads.#threads for p in 1:2 # Star parallel of two sigma functions
Threads.lock(l);
Threads.unlock(l);
arg_in_sig[p] = func_sig[p](arg_in_sig[p]);
end
.....
.....
Threads.#threads for p in 1:2
Threads.lock(l)
Threads.unlock(l)
arg_in_vel[p] = func_vel[p](arg_in_vel[p])
end
toc=time_ns();
timer[i] = toc-tic;
end # time loop
writedlm("timer.txt",timer)
return
end
What I am trying to do, is to meassure the time that takes to perform on each loop iteration, saving the result in an output file called "timer.txt". The thing is that it doesn't work.
It saves a file with all zeros on it (except two or three values, which is more confusing).
I made a toy example like:
using DelimitedFiles;
function test()
a=zeros(1000)
for i=1:1000
tic = time_ns();
C = rand(20,20)*rand(20,20);
toc = time_ns();
a[i] = toc-tic;
end
writedlm("aaa.txt",a);
return a;
end
and these actually works (it saves fine!). Is there something to do with the fact that I am implementing Threads.#threads?. What can be happening between writedlm() and time_ns() in my program?
Any help would be much apreciated!
You are iterating over it but try to save by:
timer[i] = toc-tic;
while it should be
timer[it] = toc-tic;
Perhaps you have some i in global scope and hence the code still works.
Additionally locking the thread and immediately unlocking does not seem to make much sense. Moreover, when you iterate over p which happens to be also index of the Vector cell where you save the results there is no need to use the locking mechanism at all (unless you are calling some functions that depend on a global state).
I'm creating an function to be minimized, basically a function of x1, returning value cmc. BTW I like it return some intermediate value w for later use. I just learnt to create functions return multiple values, you have to make a list, or setClass (which I'm not very clear about, so I did not use it). The executable code is
t1=1; t2=0.6; x2=1;
c=c(0,1)
f<-function(x) c(x/(t2+x),-t1*x/(t2+x)^2)
phi_c<-function(x1){
X=rbind(f(x1),f(x2))
v=solve(X%*%t(X))%*%X%*%c
w=abs(v)/sum(abs(v))
cmc=t(c)%*%solve(t(X)%*%diag(c(w))%*%X)%*%c
return(list(cmc,w))
}
phi_c(0.5)
The output is not very decent but acceptable. The problem is I cannot optimize a function with such output. So now I am doing
t1=1; t2=0.6; x2=1;
c=c(0,1)
f<-function(x) c(x/(t2+x),-t1*x/(t2+x)^2)
phi_c<-function(x1){
X=rbind(f(x1),f(x2))
v=solve(X%*%t(X))%*%X%*%c
w=abs(v)/sum(abs(v))
cmc=t(c)%*%solve(t(X)%*%diag(c(w))%*%X)%*%c
}
x1=optimize(phi_c,c(0,x2))$min
X=rbind(f(x1),f(x2))
v=solve(X%*%t(X))%*%X%*%c
w=abs(v)/sum(abs(v))
very redundant. It's ok when the problem is simple as this one, but obviously not good when things become complicated. Is there a way to create a function with multiple return values and allows you to set a prime value to be optimized? I remember some base functions are like that, give you various output but you can still work with a prime value.
Thanks.
You can just wrap this function in a different function that only returns the intended output. such as
t1=1; t2=0.6; x2=1;
c=c(0,1)
f<-function(x) c(x/(t2+x),-t1*x/(t2+x)^2)
phi_c<-function(x1){
X=rbind(f(x1),f(x2))
v=solve(X%*%t(X))%*%X%*%c
w=abs(v)/sum(abs(v))
cmc=t(c)%*%solve(t(X)%*%diag(c(w))%*%X)%*%c
return(list(cmc,w))
}
> optimize(function(x) phi_c(x)[[1]], lower = 0, upper = 5)
$minimum
[1] 4.999922
$objective
[,1]
[1,] 37.12268
I'm trying to write a script that draws Fourier sums of at least certain nicely behaving functions using Riemann sums. Ignoring the fact that my math might be seriously off at the moment, I can't seem to be able to print multiple PDF-files during the same script, which goes as follows:
"""
RepeatFunction(domain::Array{Real,1},fvals::Array{Complex{Real}},
repeatN::Int64,period::Float64=2*pi)
Builds a periodic function centered at origin in both directions from a set of
given function values, but more imporrtantly, also stretches out the domain to
accommodate this new extended array.
"""
function RepeatFunction(domain::Array{Float64,1},fvals::Array{Float64,1},
N::Int64,period::Float64=2*pi)
# Extending the domain
for n in 1:N/2
domain = [
linspace(domain[1]-period,domain[2],length(fvals));
domain;
linspace(domain[end],domain[end-1]+period,length(fvals))];
end
# Repeating the function
if N % 2 == 0
fvals = repeat(fvals,outer=[N+1]);
else
fvals = repeat(fvals, outer=[N]);
end
return domain, fvals
end
"""
RiemannSum(domain::Array{Float64},fvals::Array{Float64})::Float64
Calculates the discrete Riemann sum of a real valued function on a given
equipartitioned real domain.
"""
function RiemannSum(domain::Array{Complex{Real},1},fvals::Array{Complex{Real},1})
try
L = domain[end] - domain[1];
n = length(fvals);
return sum(fvals * L / n);
catch
println("You most likely attempted to divide by zero.
Check the size of your domain.")
return NaN
end
end
"""
RiemannSum(domain::StepRange{Real,Real},fvals::StepRange{Real,Real})::Float64
Calculates the discrete Riemann sum of a function on a given
equipartitioned domain.
"""
function RiemannSum(domain,fvals)
try
L = domain[end] - domain[1];
n = length(fvals);
return sum(fvals * L / n);
catch
println("You most likely attempted to divide by zero.
Check the size of your domain.")
return NaN
end
end
"""
RiemannSum(domain::StepRange{Real,Real},fvals::StepRange{Real,Real})::Float64
Calculates the discrete Riemann sum of a function on a given
equipartitioned domain.
"""
function RiemannSum(domain::StepRangeLen{Real,Base.TwicePrecision{Real},Base.TwicePrecision{Real}},
fvals::StepRangeLen{Real,Base.TwicePrecision{Real},Base.TwicePrecision{Real}})
try
L = domain[end] - domain[1];
n = length(fvals);
return sum(fvals * L / n);
catch
println("You most likely attempted to divide by zero.
Check the size of your domain.")
return NaN
end
end
"""
RiemannSum(domain::StepRange{Real,Real},fvals::StepRange{Real,Real})::Float64
Calculates the discrete Riemann sum of a function on a given
equipartitioned domain.
"""
function RiemannSum(domain,fvals)
try
L = domain[end] - domain[1];
n = length(fvals);
return sum(fvals * L / n);
catch
println("You most likely attempted to divide by zero.
Check the size of your domain.")
return NaN
end
end
"""
FourierCoefficient(domain,fvals)
Calculates an approximation to the Fourier coefficient for a function with
a period equal to the domain length.
"""
function FourierCoefficient(domain,fvals,n::Int64,T::Float64)
return 1/ T * RiemannSum(domain,fvals*exp(-1im * n * 1/T));
end
"""
FourierSum(domain.fvals)
Calculates the Fourier sum of a function on a given domain.
"""
function FourierSum(domain,fvals, N::Int64,T::Float64)
return [sum(FourierCoefficient(domain,fvals,n,T)*exp(1im * n * 1/T)) for n in -N:N];
end
using Plots;
pyplot()
n = 10;
T = 2*pi;
x = collect(linspace(-pi,pi,2n+1));
f = x.^2 + x;
funplot = plot(x,f);
#display(funfig)
savefig("./fun.pdf")
#println("Φ =",real(Φ))
x,repf = RepeatFunction(x,f,6,T)
repfunplot = plot(x,repf,reuse=false);
#display(repfunfig)
savefig("./repfun.pdf")
The trick mentioned here has no effect on the outcome, which is that only the first PDF gets printed. Any Julia gurus here that know what is causing the issue? I get no error messages whatsoever.
I ran the code on my system (Julia Version 0.6.1) without errors. Got 2 pdfs in my Folder: fun.pdf and repfun.pdf containing this:
Alright, I've figured out what the problem is or was. At least when coding in Juno/Atom, when Julia is first started it assumes that the working directory is /home/<username>, meaning if you issue a savefig()-command, the images are printed there.
If you wish the images to appear at a specific location, either give the absolute path to savefig, or put the line
cd("/path/to/desired/location")
at the beginning of your file.
How the first image somehow managed to appear in the desired folder still remains a mystery to me. I might have tried running Julia through bash, when working in said directory, but this must have been before I managed to get even the most rudimentary of figures to appear without issues.
Tried replicating your code, but the error is:
ERROR: LoadError: UndefVarError: StepRangeLen not defined
in include at boot.jl:261
in include_from_node1 at loading.jl:320
in process_options at client.jl:280
in _start at client.jl:378
while loading C:\Users\Евгений\Desktop\1.jl, in expression starting on line 433
There is not even line 433 in this code - very confused.
I am implementing simple modulus function on sage jupitar notebook. The function is as follows:
Mod2(v,b)=(v+b*(q-1)/2) mod q mod 2
The function is wriiten in sage as :
def modulus(v,b):
q=12289
c=[]
for i in range(len(v)):
c.append(mod(((v[i]+b[i]*(q-1)//2)%q),2))
return c
The function is executed as :
dimension = 1024 # degree of polynomials
modulus = 12289
R.<X> = PolynomialRing(GF(modulus),) Gaussian field of integers
Y.<x> = R.quotient(X^(dimension) + 1) # Cyclotomic field
pi=Y.random_element()
c=Y.random_element()
xi=Y.random_element()
sj=Y.random_element()
rj=Y.random_element()
gj=Y.random_element()
kj=((pi*c+xi)*(sj*d+rj)+(2*c*gj))
# Now, We are making another list named mon and calling the modulus function
mon=[1,2,6,5,8]
modulus(kj.list(),mon)
I get following error while executing the above code.
TypeError: 'sage.rings.integer.Integer' object is not callable
This kind of error nearly always happens when you try to do something that Sage translates as 1(3). In this case, you have redefined something!
def modulus(v,b):
versus
modulus = 12289
You can't overload things this way in Python. Sage will replace what modulus refers to by that number; your function is just gone now. So when you do
modulus(kj.list(),mon)
you are trying to call 12289 as a function.
I suggest calling your other modulus modulus1 or something like that. Do it consistently, and this problem should disappear. Good luck.